// http://hi.baidu.com/fashionapex/blog/item/a344c8cc15b8af1301e9289a.html
第一种情况是遇到默认名字空间的情况,示例文档如下:
<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://www.example.com" xmlns:ns1="http://www.example.com">
<book>
<author>tom</author>
<exauthor>
<author>robin</author>
<author>mike</author>
</exauthor>
<price>75</price>
</book>
</root>
第二种情况是遇到使用显式名字空间的情况,示例文档如下:
<?xml version="1.0" encoding="utf-8"?>
<ns1:root xmlns="http://www.example.com" xmlns:ns1="http://www.example.com">
<ns1:book>
<ns1:author>tom</ns1:author>
<ns1:exauthor>
<ns1:author>robin</ns1:author>
<ns1:author>mike</ns1:author>
</ns1:exauthor>
<ns1:price>75</ns1:price>
</ns1:book>
</ns1:root>
总的来说,大概有两种方式可以达到目的,每种方式里又可分为默认名字空间和显式名字空间区别开来,具体代码如下:
public void testXPathWithNs(){
try {
SAXReader sr = new SAXReader();
Document doc = sr.read(new FileInputStream(filename));
//使用XPath的内置函数,支持显式名字空间的两种不同方式
List res = doc.selectNodes("//*[name()='ns1:author']");
List res = doc.selectNodes("//*[local-name()='author']");
//使用XPath内置函数,支持默认名字空间的方式
List res = doc.selectNodes("//*[name()='author']");
//使用Dom4j的XPath类的方法支持显式名字空间的方式
//此方式就测试结果来说暂不支持默认名字空间的访问
Map ns = new HashMap();
ns.put("ns1", "http://www.example.com");
//加入默认名字空间到Map中
//ns.put("", "http://www.example.com");
XPath xpath = doc.createXPath("//ns1:author");
//不能够正确访问,会返回NULL值
//XPath xpath = doc.createXPath("//author");
xpath.setNamespaceURIs(ns);
List res = xpath.selectNodes(doc);
System.out.println("Size: "+res.size());
if(res.size() != 0){
for(int i = 0; i < res.size(); i++){
Element tmp = (Element)res.get(i);
System.out.println("element["+i+"] name: "+tmp.getName());
System.out.println("element["+i+"] parent name: "+
tmp.getParent().getName());
}
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}