Quick revision
The short answer
We create an XPath object with XPathFactory.newInstance().newXPath(), evaluate "/catalog/book[price > 30]/title" against the Document asking for XPathConstants.NODESET, and loop over the resulting NodeList collecting getTextContent() of each node into a List<String>. Expressions we reuse should be compiled once with xp.compile(), XPath objects are not thread-safe, and since Java 9 evaluateExpression() with XPathNodes gives a typed result.
What to remember
In this answer, we wrote a method that evaluates /catalog/book[price > 30]/title with javax.xml.xpath, asks for a NODESET, and collects each node's text content into a List<String>. We saw that the comparison converts price text to a number, so non-numeric prices become NaN and are silently excluded, that reused expressions should be compiled once, and that XPath and XPathExpression objects are not thread-safe, so we keep one per thread. Since Java 9, evaluateExpression with XPathNodes gives typed results without casting.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We create an XPath object with XPathFactory.newInstance().newXPath(), evaluate "/catalog/book[price > 30]/title" against the Document asking for XPathConstants.NODESET, and loop over the resulting NodeList collecting getTextContent() of each node into a List<String>. Expressions we reuse should be compiled once with xp.compile(), XPath objects are not thread-safe, and since Java 9 evaluateExpression() with XPathNodes gives a typed result.
Why this question is asked
XPath is the query language for XML: one short expression replaces a dozen lines of loops over child nodes. Many integration services use it to pull a few values out of partner documents, so interviewers often ask for a small working example and then probe the details that cause production bugs, such as type conversion and thread safety. In this answer, we will recap the parts of an XPath expression, write the method, look at how the comparison with 30 really works, compile and reuse expressions safely, and finish with the typed API added in Java 9.
1A Quick Recap of XPath
An XPath expression describes a path through the document tree. /catalog/book means book elements that are children of the root catalog element. A predicate in square brackets filters the nodes: book[price > 30] keeps only the books whose price child is greater than 30. Then /title steps down to the title child of each remaining book.
Java's standard XPath support lives in javax.xml.xpath and implements XPath 1.0. It evaluates expressions over a DOM tree, so we first parse the document into a Document, and then ask XPath for a result type: a node set, a single node, a string, a number or a boolean.
We will use this catalog throughout. Notice the last book: its price is not a number, which will matter in a moment.
2Writing the Method
Here is the complete method, from a parsed Document to a List<String>.
- Select /catalog/book4 book elements
- For each book, take price as a number25, 45.5, 31, NaN
- Is the number greater than 30?YesKeep the bookNoDrop the book
- Step down to title2 title elements
- Return NodeListSpring in Depth, XML Internals
5 steps in order. Play them, or step through them one at a time.
evaluate() returns Object, because the result type depends on the constant we pass, so we cast to NodeList for NODESET. getTextContent() returns the text inside each title element. The order of the results follows document order, which is usually what we want.
3How the Comparison With 30 Works
The predicate price > 30 compares a node with a number. XPath 1.0 handles this by converting the text of the price element to a number and comparing numbers. That is why 31 and 45.50 match while 25.00 does not.
But there is a catch. When the text is not a valid number, such as n/a, an empty element or a value with a currency symbol like $45 or a comma like 45,50, the conversion gives NaN, not a number, and every comparison with NaN is false. So book 4 is silently left out, with no error and no warning. If the business expects bad prices to be reported, we must check for them separately, for example with /catalog/book[string(number(price)) = 'NaN'] to find books with unusable prices.
One more detail: if a book had two price children, price > 30 would be true if any of them is greater than 30, because comparisons with node sets in XPath 1.0 are existential. That surprises people who expect only the first one to count.
4Compiling and Reusing Expressions Safely
Parsing an expression string costs time. When the same expression runs on thousands of documents, we compile it once into an XPathExpression and reuse it.
The JDK documentation states that XPath objects, and the XPathExpression objects compiled from them, are not thread-safe and must not be used by several threads at the same time. In a web service, sharing one static XPath across request threads can produce wrong results or exceptions under load. A ThreadLocal, a small pool, or simply creating the XPath per request (cheap compared to parsing the document) avoids that. The factory itself is also not guaranteed thread-safe, so we either create it per use or make sure it is only used from one place at a time; check your version's documentation if you share it.
5Typed Results Since Java 9
Java 9 added evaluateExpression(), which takes a Class for the result type and avoids the cast from Object. For node sets it returns XPathNodes, which is Iterable<Node>, so we can use a for-each loop.
Notice the last line: sum() over a set that includes a non-numeric value returns NaN, the same conversion rule as before, this time spoiling the whole total. It is a good reminder to validate numeric fields before relying on XPath arithmetic.
6Follow-up questions
What is the difference between //book and /catalog/book?
//book searches the whole document at any depth, so it would also find book elements nested deep inside other elements, and it has to visit every node. /catalog/book only looks at children of the root. For large documents and precise semantics, an absolute path is better.
How do I get a single value instead of a node set?
Ask for XPathConstants.STRING or NUMBER, or use evaluateExpression with String.class or Double.class. For example string(/catalog/book[@id='2']/title) returns Spring in Depth. With STRING, an empty result gives an empty string rather than null, so we check for that.
Does this work with namespaces?
Only if the document is parsed with a namespace-aware DocumentBuilderFactory and we set a NamespaceContext that maps prefixes to the namespace URIs used in the document, then write /c:catalog/c:book in the expression. Without that, a document with a default namespace returns no matches.
7Conclusion
In this answer, we wrote a method that evaluates /catalog/book[price > 30]/title with javax.xml.xpath, asks for a NODESET, and collects each node's text content into a List<String>. We saw that the comparison converts price text to a number, so non-numeric prices become NaN and are silently excluded, that reused expressions should be compiled once, and that XPath and XPathExpression objects are not thread-safe, so we keep one per thread. Since Java 9, evaluateExpression with XPathNodes gives typed results without casting.
Open with
I would get an XPath from XPathFactory.newInstance().newXPath(), and evaluate the expression /catalog/book[price > 30]/title against the Document with XPathConstants.NODESET. That returns an Object, which I cast to NodeList, then I loop from zero to getLength and add item(i).getTextContent() to an ArrayList.
Then, if they want more
The predicate in square brackets filters books, and the last step selects their title children. A few details matter in practice. The comparison price greater than 30 converts the element's text to a number, so a price like n/a, an empty element, or a value with a currency sign becomes NaN and the comparison is simply false.
Those books disappear silently, so if bad data must be reported, I would check for it separately. If I run the same expression many times, I compile it once into an XPathExpression.
But XPath and XPathExpression are not thread-safe, so in a web service I would keep one per thread with a ThreadLocal or create them per request, never share a static one. And since Java 9 there is evaluateExpression, where I pass XPathNodes.class and get an Iterable of nodes, so I can use a for-each loop with no cast.
If the document has namespaces, I also need a namespace-aware parser and a NamespaceContext.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Using javax.xml.xpath, select all titles of books with price greater than 30 from a...": https://scrivio-interview-library.netlify.app/java/xml-processing/5d545aa955/