1

Possible Duplicate:
Sending XPath a variable from Java

When I run this expression:

    XPathExpression xpe = xpath.compile("//bb[name/text()='k2']/value");    

It works fine.

But when I try to plant my own variable (instead of 'k2') like this:

    XPathExpression xpe = xpath.compile("//bb[name/text()=" + c_name +"]/value");

tt doesn't work.

I assume the problem is that the working expression syntax contain 'k2' while the second dont appear that way.

Any ideas how to plant the variable correctly? i tried putting String and Character[] both dont work.

Community
  • 1
  • 1
Michael A
  • 5,770
  • 16
  • 75
  • 127

1 Answers1

3
"//bb[name/text()='" + c_name +"']/value"

Note the single quotes surrounding the reference to c_name.

You could argue that the alternative using String.format()

 "//bb[name/text()='%s']/value".format(c_name)

is more readable.

As dogbane notes, this won't work if the variable value contains quotes itself. For a more complex but safer solution see this SO answer.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • 1
    -1 won't work if name is `Scarlett O'Hara`. – dogbane Oct 04 '12 at 11:32
  • Of course. Noted and referenced an appropriate solution – Brian Agnew Oct 04 '12 at 11:37
  • Constructing XPath expressions by string concatenation leaves you exposed to injection attacks. It's much better to use variables. – Michael Kay Oct 04 '12 at 13:27
  • @Michael - acknowledged and that's why I referenced the additional answer. Of course your exposure to attacks is dependent upon your source of variable texts, and consequently different solutions are appropriate for different scenarios – Brian Agnew Oct 04 '12 at 13:31