dom4j中使用xpath解析带命名空间的xml文件,取不到节点的解决办法

XML文件如下:

<?xml version="1.0" encoding="gbk" standalone="yes"?> <unit xmlns="http://www.sdml.info/srcML/src" xmlns:cpp="http://www.sdml.info/srcML/cpp"> <cpp:ifndef> <name>test</name> </cpp:ifndef> <class>class</class> </unit>

解析代码如下:

public static void main(String [] args){ Document document = XmlTools.getDoc(file.getPath()); HashMap xmlMap = new HashMap(); xmlMap.put("src", "http://www.sdml.info/srcML/src"); xmlMap.put("cpp", "http://www.sdml.info/srcML/cpp"); // 以下可以访问到 XPath x0 = document.createXPath("unit/src:class"); XPath x1 = document.createXPath("src:unit/src:class"); XPath x2 = document.createXPath("/unit/src:class"); XPath x3 = document.createXPath("unit/src:class"); XPath x4 = document.createXPath("/unit/cpp:define"); XPath x6 = document.createXPath("unit/cpp:define"); XPath x7 = document.createXPath("src:unit/cpp:define"); // 以下访问不到 XPath x8 = document.createXPath("unit/class"); XPath x9 = document.createXPath("unit/define"); XPath x10 = document.createXPath("/unit/class"); XPath x11 = document.createXPath("/unit/define"); XPath x12 = document.createXPath("src:unit/class"); XPath x13 = document.createXPath("src:unit/define"); XPath x14 = document.createXPath("unit/cpp:class"); XPath x15 = document.createXPath("unit/src:define"); test(x0, document, xmlMap); test(x1, document, xmlMap); test(x2, document, xmlMap); test(x3, document, xmlMap); test(x4, document, xmlMap); test(x6, document, xmlMap); test(x7, document, xmlMap); test(x8, document, xmlMap); test(x9, document, xmlMap); test(x10, document, xmlMap); test(x11, document, xmlMap); test(x12, document, xmlMap); test(x13, document, xmlMap); test(x14, document, xmlMap); test(x15, document, xmlMap); } static void test(XPath x, Document doc, Map map) { x.setNamespaceURIs(map); System.out.println("运行结果:"+x.selectNodes(doc).size()); }

运行结果如下:

运行结果:1 运行结果:1 运行结果:1 运行结果:1 运行结果:1 运行结果:1 运行结果:1 运行结果:0 运行结果:0 运行结果:0 运行结果:0 运行结果:0 运行结果:0 运行结果:0 运行结果:0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值