xml文件中存在命名空间致使 document.selectNodes("//linuxidc/book") 无返回结果
如:
<linuxidc xmlns="http://www.linuxidc.com">
<book>
<title></title>
<des></des>
...
</book>
</linuxidc>node
推荐阅读:linux
dom4j+xpath读取xml文件配置Oracle数据库链接 http://www.linuxidc.com/Linux/2013-04/83405.htmweb
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服务器
解决方法:dom
// 得到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);spa