dom4j解析带命名空间的xml
当我们解析xml的时候,如果该xml没有带命名空间,那么很好解析,直接用dom4j的selectNodes(XPath表达式)既可以了。但是如果命名空间那么则会返回空。下面为大家介绍三种方法来解决:
第一种:
<report xmlns="http://www.eclipse.org/birt/2005/design" version="3.2.15" id="1">
<list-property name="cssStyleSheets">
<structure>
<property name="fileName">D: eport.css</property>
</structure>
</list-property>
</report>
<list-property name="cssStyleSheets">
<structure>
<property name="fileName">D: eport.css</property>
</structure>
</list-property>
</report>
第一个方案.设置你的xpath的命名空间setNamespaceURI
public class TransferXML {
public static void main(String[] args) throws Exception//design:list-property");//填写XPath表达式
x.setNamespaceURIs(map);//设置命名空间
List nodelist = x.selectNodes(document);//取出符合规定的集合
System.out.println(nodelist.size());
}
}
public static void main(String[] args) throws Exception//design:list-property");//填写XPath表达式
x.setNamespaceURIs(map);//设置命名空间
List nodelist = x.selectNodes(document);//取出符合规定的集合
System.out.println(nodelist.size());
}
}
第二种:设置你的DocumentFactory()的命名空间 setXPathNamespaceURIs
public class TransferXML {
public static void main(String[] args) throws Exception{
Map map = new HashMap();
map.put("design","http://www.eclipse.org/birt/2005/design");//填充map
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);//设置命名空间
Document document = saxReader.read(file);
List tmp = document.selectNodes("//design:list-property");//用XPath选取节点
System.out.println(tmp.size());
}
}
public static void main(String[] args) throws Exception{
Map map = new HashMap();
map.put("design","http://www.eclipse.org/birt/2005/design");//填充map
SAXReader saxReader = new SAXReader();
File file = new File("D:\test.xml");
saxReader.getDocumentFactory().setXPathNamespaceURIs(map);//设置命名空间
Document document = saxReader.read(file);
List tmp = document.selectNodes("//design:list-property");//用XPath选取节点
System.out.println(tmp.size());
}
}
详细请参考:http://blog.sina.com.cn/s/blog_4bf2e5550100sbb7.html
相关推荐
周公周金桥 2020-09-06
大象从不倒下 2020-07-31
AlisaClass 2020-07-19
MaureenChen 2020-04-21
xingguanghai 2020-03-13
teresalxm 2020-02-18
木四小哥 2013-05-14
SoShellon 2013-06-01
Simagle 2013-05-31
羽化大刀Chrome 2013-05-31
waterv 2020-01-08
LutosX 2013-07-29
vanturman 2013-06-27
wutongyuq 2013-04-12
luoqu 2013-04-10
today0 2020-09-22
89520292 2020-09-18
bigname 2020-08-25