dom4j中通过xpath处理带命名空间的XML文件

1.XML的命名空间:

许多XML配置文件中,通常在开头部分带有命名空间,如spring中:

[html]  view plain copy
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:aop="http://www.springframework.org/schema/aop"  
  4.        xmlns:tx="http://www.springframework.org/schema/tx"  
  5.        xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  8.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"  
  9.        default-lazy-init="true">  
  10.   
  11. </beans>  

在spring中,解析节点使用lazy loading方式:即先获取root节点,然后依次获取其子节点解析。在处理每个bean的命名空间时,会取其namespace与字符串“http://www.springframework.org/schema/beans”比较,以判断是否为对应spring的bean节点。一般其它情况并不存在需要对namespace进行处理

见:org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.isDefaultNamespace()


2.若要使用dom4j处理带namespace的xml文件,通过遍历根节点方式不影响命名空间。

而若通过普通的xpath方式查询,则必须对xpath进行预处理:

首先,将namespace放入map,设置到DocumentFactory

[java]  view plain copy
  1. SAXReader reader1 = new SAXReader();  
  2.   
  3. Map<String, String>map=new HashMap<String, String>();  
  4. map.put("abc","http://www.springframework.org/schema/beans");  
  5.   
  6. reader1.getDocumentFactory().setXPathNamespaceURIs(map);  

然后,当通过xpath查询节点或attribute时,需要将所有的节点属性前加上先前设置的map键值(attribute名不需要加)

eg,查询xpath: beans/bean[@id='root']

[java]  view plain copy
  1. Element root=(Element) document.selectSingleNode("abc:beans/abc:bean[@id='root']");  
或者: //bean[@id='root']

[java]  view plain copy
  1. Element root=(Element) document.selectSingleNode("//abc:bean[@id='root']");  

当然,可以使用正则表达式对原xpath进行转换

[java]  view plain copy
  1. public static String getXMLNameSpaceFixed(String xpath)  
  2. {  
  3.     xpath= xpath.replaceAll("/(\\w)""/"+"abc:$1");//replace start with "/"  
  4.     xpath= xpath.replaceAll("^(\\w)""abc:$1");    //replace start with word  
  5.     return xpath;  
  6. }  

3.当处理另一个文档,此时若只是SAXReader reader2 = new SAXReader(),会发现仍然沿用原先的map;

而且重新设置新的namespace的map后,原有的reader1的xpath查询失效。

原因是,dom4j中默认的SAXReader初始化时调用DocumentFactory的单例对象,

因此必须使用新的工厂避免对原有工厂的影响:

[java]  view plain copy
  1. SAXReader reader2 = new SAXReader(new DocumentFactory());  
  2.   
  3. Map<String, String>map=new HashMap<String, String>();  
  4. map.put("xyz","http://www.springframework.org/schema/beans");  
  5.   
  6. reader2.getDocumentFactory().setXPathNamespaceURIs(map);  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值