1

If I provide constant "1" in rollnumber[1]

/root/person/rollnumber[1]

XPath evaluates fine.

But instead of a constant, I want to provide some variable

/root/person/rollnumber[$i]

where $i can be any integer.

This XPath expression does not work.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
ankit
  • 363
  • 2
  • 7
  • 16
  • How/Where did you set the value of `$i`? – har07 Apr 28 '16 at 05:24
  • I am writing this xpath in velocity tempalte. so, i can set it #set($i = 1) – ankit Apr 28 '16 at 05:30
  • Since `$i` is a velocity template's variable, I strongly suspect this is velocity-specific question. XPath 1.0 itself doesn't have notion of `$` variable – har07 Apr 28 '16 at 05:44
  • Yes you are right. seems like xpath doesn't have notion of $ variable. i saw one eg which says $ can be used. but it's not working. – ankit Apr 28 '16 at 06:35

1 Answers1

0

The usual trick is to assemble the XPath using string formatting or concatenation within the hosting language environment.

Try this in Velocity:

#set($xp = "/root/person/rollnumber[${i}]")

Then use $xp in place of the string literal in your XPath call.

See also How to pass parameter into XPath expression in Xpath 1.0 for how to do this in other hosting languages.

Community
  • 1
  • 1
kjhughes
  • 106,133
  • 27
  • 181
  • 240