我正在计算我为特定 xpath 获得了多少个节点,然后遍历这些节点。
对于特定的 xpath,计数为 6。前 4 个节点将显示值。当我到达第 5 和第 6 时,我得到空值。
XML 大致如下所示
<account>
<contact>
<contact>
<contact>
<contact>
</account>
<account>
<contact>
<contact>
</account>
下面是一个代码片段:
String count = xpath.evaluate("count("+genericPath+")", LegacyXML);
System.out.println("count " +count);
for (int a = 1; a <= Integer.valueOf(count); a++){
XPathExpression genPath = xpath.compile(genericPath+"["+a+"]");
Object result = genPath.evaluate(LegacyXML, XPathConstants.NODE);
Node nodes = (Node) result;
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
try{
doc.appendChild(doc.importNode(nodes, true));
System.out.println("this is eval result :) "+ xpath.evaluate(genericPath+"["+a+"]", LegacyXML).toString());
}catch(NullPointerException e){
System.out.println("Please ensure that the hierarchy code of" +PKattribute+ " in " +LegacyAPI + " is correct. It doesn't point to an array.");
System.out.println("this is eval result :( "+ xpath.evaluate(genericPath+"["+a+"]", LegacyXML).toString());
}
所以我正确地获得了前 4 个节点,最后两个为空。当我打开 XML 并查看它时,显然存在值。在各种在线 xPath 上测试变量 'genericPath' 计算返回 6 个带有值的节点。我错过了什么?
任何帮助将不胜感激。
编辑:泛型路径 =//*联系人
如果通用路径//contact
则它将选择 6 个元素。
//contact[N]
选择作为其父级的第 N 个子联系人的每个联系人。因此,//contact[5]
和//contact[6]
不选择任何内容。
你想要(//contact)[N]
.
使用字符串连接反复构造这样的表达式效率非常低。像这样解析和编译 XPath 表达式所需的时间可能是执行它的 100 倍。使用可在运行时提供的参数编译单个表达式要好得多。或者更好的是,计算返回所有六个元素的单个表达式。