I am using the following XPath expression to loop through a XML document:
/templatedatabase/datatypes/integers/integer[index]/@defaultvalue
Method header:
private static String getGetDefaultValueByIndex(Document doc, XPath xpath, int index)
"index" is a parameter in the method. The problem is the following:
The query doesn´t return a value if I put a number in the method header as parameter.(e.g. getGetDefaultValueByIndex(doc, xpath, 1)).
But if I, for instance put a number like 1,2,... in place of index in the query I get the data I want from the XML file while executing the same method. The XPath query is correct and the method is working if I put in the number manually in the query like this:
/templatedatabase/datatypes/integers/integer[1]/@defaultvalue
--> This returns a value.
However:
getGetDefaultValueByIndex(doc, xpath, 1)
/templatedatabase/datatypes/integers/integer[index]/@defaultvalue
--> This doesn´t return a value.
I don´t really understand why this is not working. I can´t imagine that you can´t loop through a XPath Query using a variable.
The complete code of the method:
private static String getGetDefaultValueByIndex(Document doc, XPath xpath, int index) {
String DefaultValue = null;
try {
String expression = "/templatedatabase/datatypes/integers/integer" + "[index]" + "/@defaultvalue";
DefaultValue = (String) xPath.evaluate(expression, doc, XPathConstants.STRING);
System.out.println(DefaultValue);
} catch(XPathExpressionException e) {
e.printStackTrace();
}
return DefaultValue;
}
}