DOM4J解析xml

cookqq 发布于 2012/06/21 14:35
阅读 292
收藏 0

解析xml文件,

要解析的文件如下

<?xml version="1.0" encoding="utf-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" default-autowire="byName">
  
  
  <bean id="userService" class="com.bug.service.impl.UserServiceImpl"/>
  <bean id="bookService" class="com.bug.service.impl.BookServiceImpl"/>
  <bean id="sortService" class="com.bug.service.impl.SortServiceImpl"/>
</beans>
解析的代码:
        SAXReader reader = new SAXReader();
		  Document document = null;
		  document = reader.read("applicationContext-service.xml"));
		  DefaultXPath beansPath = new DefaultXPath("/beans");
		  List<Element> beans = beansPath.selectNodes(document);
		  if(beans.size()==0){
			  System.out.println("---error--insertSpringService() no find beans");
			  return;
		  }
		  Element _beans = beans.get(0);

		  List<Element> beanEs = document.selectNodes("//bean");
		 
		  Boolean isExit = false;
		  String findId = table.toLowerCase()+"Service";
		  for (Element mapping : beanEs) {
			if(mapping.attributeValue("id").equals(findId)){
				isExit = true;
				break;
			}
		  }

这里的值不知道beanEs为什么总是空


加载中
0
cookqq
cookqq

怎么没有人回答啊?

 

0
cookqq
cookqq
补充一下jar包是:DOM4J-1.6.1.jar
0
悟方向
悟方向

原因是因为这个XML有个命 名空间  我刚刚把你的代码修改了一下  测试了一下 应当是可以的 你测试一下

@Test 
	public void testXpath() throws DocumentException {
		Map map = new HashMap();
		map.put("beansns", "http://www.springframework.org/schema/beans");
		SAXReader reader = new SAXReader();
		reader.getDocumentFactory().setXPathNamespaceURIs(map);
		Document document = null;
		document = reader
				.read("dest.xml");
		DefaultXPath beansPath = new DefaultXPath("/beans");
		List<Element> beans = beansPath.selectNodes(document);
		if (beans.size() == 0) {
			System.out.println("---error--insertSpringService() no find beans");
			return;
		}
		Element _beans = beans.get(0);
		System.out.println(_beans.getName());

		List<Element> beanEs = _beans.selectNodes("beansns:bean");
		System.out.println(beanEs.size());
		Boolean isExit = false;
		String table = "";
		String findId = table.toLowerCase() + "Service";
		for (Element mapping : beanEs) {
			if (mapping.attributeValue("id").equals(findId)) {
				isExit = true;
				break;
			}
		}
	}

返回顶部
顶部