java Dom4j selectNodes(arg) 不提供节点列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14317384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dom4j selectNodes(arg) don't give list of nodes
提问by user1808932
I am using DOM4j for XML work in java, my xml is like this:
我在 Java 中使用 DOM4j 进行 XML 工作,我的 xml 是这样的:
<?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.
获取列表零的大小。我觉得这是由于 xml 中指定的命名空间。我尝试了很多,但没有成功。
回答by Ian Roberts
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:
XPath 表达式中不带前缀的元素名称指的是不在命名空间中的元素——它们不考虑xmlns="..."
文档中声明的“默认”命名空间。您需要在 XPath 引擎中为命名空间声明一个前缀,然后在表达式中使用该前缀。这是一个受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);
回答by Achyut
Modify your code :
修改您的代码:
List<Node>list = document.selectNodes("//abcd/efg");