JavaBits JavaBits - 1 month ago 6
Java Question

How to use Java String variables inside XPath query

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!

Answer
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.