JavaBits JavaBits - 2 months ago 14
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!

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.