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);
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']");
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; }
而且重新设置新的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);