Dom4j selectNodes(arg) don't give list of node

2019-04-07 14:02发布

I am using DOM4j for XML work in java, my xml is like this:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<abcd name="ab.catalog" xmlns="http://www.xyz.com/pqr" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.xyz.com/pqr ./abc.xyz.xsd">             
<efg>
......
</efg>
<efg>
.....
</efg>
</abcd>

then,

List<Node>list = document.selectNodes("/abcd/efg");

gets the size of list zero. I feel it's due to namespace specified in the xml. I tried a lot but cn't get success.

2条回答
何必那么认真
2楼-- · 2019-04-07 14:44

Modify your code :

List<Node>list = document.selectNodes("//abcd/efg");
查看更多
走好不送
3楼-- · 2019-04-07 14:51

Unprefixed element names in XPath expressions refer to elements that are not in a namespace - they do not take account of the "default" xmlns="..." namespace declared on the document. You need to declare a prefix for the namespace in the XPath engine and then use that prefix in the expression. Here is an example inspired by the DOM4J javadocs:

Map uris = new HashMap();
uris.put("pqr", "http://www.xyz.com/pqr");
XPath xpath = document.createXPath("/pqr:abcd/pqr:efg");
xpath.setNamespaceURIs(uris);
List<Node> nodes = xpath.selectNodes(document);
查看更多
登录 后发表回答