您的位置:首页 > Web前端 > Node.js

Dom4j 存在命名空间导致document.selectNodes() 无返回结果

2016-04-08 00:00 666 查看
摘要: dom4j,selectNodes,xpath

xml文件中存在命名空间导致 document.selectNodes("//linuxidc/book") 无返回结果
如:
<linuxidc xmlns="http://www.linuxidc.com">
<book>
<title></title>
<des></des>
...
</book>
</linuxidc>
推荐阅读:
dom4j+xpath读取xml文件配置Oracle数据库连接 http://www.linuxidc.com/Linux/2013-04/83405.htm
Struts2+jQuery+Dom4j实现服务器返回Xml文档 http://www.linuxidc.com/Linux/2012-07/65680.htm
Java使用dom4j解析XML字符串 http://www.linuxidc.com/Linux/2013-07/87734.htm
解决方法
// 获得xml对象
Document doc = DocumentHelper.parseText(xml);
Map map = new HashMap();
// 获得命名空间
String nsURI = doc.getRootElement().getNamespaceURI();
map.put("xmlns", nsURI);
// 创建解析路径,就是在普通的解析路径前加上map里的key值
XPath x = doc.createXPath("//xmlns:linuxidc/xmlns:book");
x.setNamespaceURIs(map);
// 这样就拿到结果了
List<Node> nodes = x.selectNodes(doc);
Node node = x.selectSingleNode(doc);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dom4j xml xpath