简体   繁体   English

Java中的XPath将不接受表达式中的变量

[英]XPath in java won't accept variable in expression

Can someone be kind enough to explain me why 有人能对我解释一下吗
xPath.evaluate("/MEMBER_LIST/MEMBER[1]/ADDRESS", nodeMemberList, XPathConstants.STRING) Returns the value I'm looking for and why xPath.evaluate("/MEMBER_LIST/MEMBER[" + i + "]/ADDRESS", nodeMemberList, XPathConstants.STRING) Returns an empty String? xPath.evaluate(“ / MEMBER_LIST / MEMBER [1] / ADDRESS”,nodeMemberList,XPathConstants.STRING)返回我要查找的值以及为什么xPath.evaluate(“ / MEMBER_LIST / MEMBER [” + i +“] / ADDRESS “,nodeMemberList,XPathConstants.STRING)返回空字符串? I have to do these in a for loop so here "i" is an int representing the current entry. 我必须在for循环中执行这些操作,因此这里的“ i”是一个表示当前条目的整数。

Does your for loop start at 1? 您的for循环是否从1开始? The expression /MEMBER_LIST/MEMBER[0] isn't a valid XPath expression because XPath indexes start at 1. Also, accessing an index which exceeds the total number of nodes is invalid. /MEMBER_LIST/MEMBER[0]表达式不是有效的XPath表达式,因为XPath索引从1开始。而且,访问超出节点总数的索引也是无效的。 For example, executing /MEMBER_LIST/MEMBER[5] when there are only 3 MEMBER elements. 例如,当只有3个MEMBER元素时,执行/MEMBER_LIST/MEMBER[5]

You can also use the XPathConstants.NODESET constant. 您还可以使用XPathConstants.NODESET常量。 This will return a list of all elements that match the given expression. 这将返回与给定表达式匹配的所有元素的列表。 You can then iterate over the list. 然后,您可以遍历列表。

NodeList nodeList = (NodeList)xPath.evaluate("/MEMBER_LIST/MEMBER/ADDRESS", nodeMemberList, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); ++i){
  Node node = nodeList.item(i);
  String address = node.getTextContent();
}

如果i==0则答案将为空,因为XPath索引从1开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM