java - Using XPath Expression in Loop -
i using following xpath expression loop through xml document:
/templatedatabase/datatypes/integers/integer[index]/@defaultvalue
method header:
private static string getgetdefaultvaluebyindex(document doc, xpath xpath, int index)
"index" parameter in method. problem following: query doesn´t return value if put number in method header parameter.(e.g. getgetdefaultvaluebyindex(doc, xpath, 1)
).
but if i, instance put number 1,2,... in place of index in query data want xml file while executing same method. xpath query correct , method working if put in number manually in query this:
/templatedatabase/datatypes/integers/integer[1]/@defaultvalue
--> returns value.
however:
getgetdefaultvaluebyindex(doc, xpath, 1) /templatedatabase/datatypes/integers/integer[index]/@defaultvalue
--> doesn´t return value.
i don´t understand why not working. can´t imagine can´t loop through xpath query using variable.
the complete code of 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; }
}
you've got quotes in wrong place, try:
string expression = "/templatedatabase/datatypes/integers/integer[" + index + "]/@defaultvalue";
this include value of index
parameter xpath expression, rather literal string "index"
.
a word of warning though - constructing xpath expressions dynamically using string concatenation fine when you're dealing numeric variables index
, if want provide arbitrary user-specified string parameters expression it's safer use static xpath expression including xpath variables like
"/templatedatabase/datatypes[@name=$targetname]"
and define xpathvariableresolver
inject actual values.
Comments
Post a Comment