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

1.XML的命名空间:

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

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
       default-lazy-init="true">

</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

SAXReader reader1 = new SAXReader();

Map<String, String>map=new HashMap<String, String>();
map.put("abc","http://www.springframework.org/schema/beans");

reader1.getDocumentFactory().setXPathNamespaceURIs(map);

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

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

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

Element root=(Element) document.selectSingleNode("//abc:bean[@id='root']");

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

	public static String getXMLNameSpaceFixed(String xpath)
	{
		xpath= xpath.replaceAll("/(\\w)", "/"+"abc:$1");//replace start with "/"
		xpath= xpath.replaceAll("^(\\w)", "abc:$1");    //replace start with word
		return xpath;
	}

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

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

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

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

SAXReader reader2 = new SAXReader(new DocumentFactory());

Map<String, String>map=new HashMap<String, String>();
map.put("xyz","http://www.springframework.org/schema/beans");

reader2.getDocumentFactory().setXPathNamespaceURIs(map);


  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值