首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

DOM4J读取xml制定节点有关问题

2013-09-17 
DOM4J读取xml制定节点问题xml内容如下:?xml version1.0 encodingUTF-8 ?beans xmlnshttp://www

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">
<beanclass="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">
<beanclass="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的时候就要注意加上命名空间的前缀这样才能正确的读取到



SAXReader reader=new SAXReader();
Document doc=reader.read(new File(你的xml路径));
//获取命名空间
String namespace=doc.getRootElement().getNamespaceURI();
/*
*创建XPath表达式加上命名空间这个前缀,由于楼主的xml没有定义命名空间的前缀,那么就可以自己随意
*取名,如果有定义前缀那这里就要用doc.getRootElement().getNamespacePrefix()来获取前缀了后面*的表达式都要跟上这个前缀
*/
XPath xpath=doc.createXPath("/beans/ns:bean/ns:property[@name='interceptorNames']/ns:list");
Map map = new HashMap();
map.put("ns",namespace);//给命名空间设置一个前缀
xpath.setNamespaceURIs(map);//把命名空间加入XPath中
Node node=xpath.selectSingleNode(doc);
System.out.println(node.asXML());

热点排行