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? I have to do these in a for loop so here "i" is an int representing the current entry.

Answers


Does your for loop start at 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. For example, executing /MEMBER_LIST/MEMBER[5] when there are only 3 MEMBER elements.

You can also use the XPathConstants.NODESET constant. 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();
}

If i==0 the answer will be empty as XPath indexes start at 1.


Need Your Help

How to find which build paths a project is on

java eclipse build classpath buildpath

Suppose I have a Java project in Eclipse called ProjectA. I have 50 other projects and I want a list of projects that have ProjectA as part of their build path.

Use output of one function and average it in another function

python python-3.x

please keep in mind that while I showcase my code, that I am fairly new to programming. So please forgive any problems. I am writing a piece of python code that uses the output of one function and ...