日期:2014-05-20  浏览次数:20698 次

DOM4J读取xml制定节点问题
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.0.xsd">
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<value>*Svr,*Svc</value>
</property>
<property name="interceptorNames">
<list>
</list>
</property>
</bean>
</beans>

需求是要在list节点内动态的追加节点内容,所以想直接获取到list这个节点
用如下方法为何获取都得是null:
Document XmlDoc = new SAXReader().read(new File(xmlPath));
Element e = XmlDoc.getRootElement();
System.out.println(e.selectSingleNode("/beans/bean/property[@name='interceptorNames']"));

求解
dom4j?xml?java

------解决方案--------------------
引用:
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.0.xsd">
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<value>*Svr,*Svc</value>
</property>
<property name="interceptorNames">
<list>
</list>
</property>
</bean>
</beans>

需求是要在list节点内动态的追加节点内容,所以想直接获取到list这个节点
用如下方法为何获取都得是null:
Document XmlDoc = new SAXReader().read(new File(xmlPath));
Element e = XmlDoc.getRootElement();
System.out.println(e.selectSingleNode("/beans/bean/property[@name='interceptorNames']"));

求解

楼主看来对xml的命名空间理解不够,楼主的xml中出现了xmlns="http://www.springframework.org/schema/beans"命名空间的定义。这时用XPath的时候就要注意加上命名空间的前缀这样才能正确的读取到