How to use the Java string variables in the XPath query

advertisements

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

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()";

or

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

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