JavaBits JavaBits - 1 year ago 64
Java Question

How to use Java String variables inside XPath query

I have

file which contains author name and book titles. I am using the following code snippet to query

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr
= xpath.compile("//book[author= 'Larry Niven']/title/text()");

Now instead of directly putting the name in the query if I want to pass it while the program is running as a String variable how to do it. Just putting the string variable name is not working!

Answer Source
String rawXPath = "//book[author= '" + larrysName + "']/title/text()";


String rawXPath = String.format("//book[author= '%s']/title/text()", larrysName);

where larrysName is a variable of type String coming from somewhere.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download