Note that there are some explanatory texts on larger screens.

plurals
  1. PORunning XPath on child node
    primarykey
    data
    text
    <p>I'm trying to do a xpath lookup on nodes returned by xpath lookup, but it doesn't seem to work as I expected.XPaths executed on the child nodes of a document seem to be executd against hthe root node of the document (in the example, the inventory tag.), instead of the root of the provided node.</p> <p>Am I missing something here? I'm new to XPath.</p> <p>Also, please don't answer "just do //book[author='Neal Stephenson'/title". I have a legitimate use case, and this is a simplified example.</p> <p>Code snippet</p> <pre><code>DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse("src/main/java/books.xml"); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Node book = (Node) xpath.evaluate("//book[author='Neal Stephenson']", doc, XPathConstants.NODE); Node title = (Node) xpath.evaluate("/title", book, XPathConstants.NODE); // I get null here. Node inventory = (Node) xpath.evaluate("/inventory", book, XPathConstants.NODE); // this returns a node. </code></pre> <p>book.xml</p> <pre><code>&lt;inventory&gt; &lt;book year="2000"&gt; &lt;title&gt;Snow Crash&lt;/title&gt; &lt;author&gt;Neal Stephenson&lt;/author&gt; &lt;publisher&gt;Spectra&lt;/publisher&gt; &lt;isbn&gt;0553380958&lt;/isbn&gt; &lt;price&gt;14.95&lt;/price&gt; &lt;/book&gt; &lt;book year="2005"&gt; &lt;title&gt;Burning Tower&lt;/title&gt; &lt;author&gt;Larry Niven&lt;/author&gt; &lt;author&gt;Jerry Pournelle&lt;/author&gt; &lt;publisher&gt;Pocket&lt;/publisher&gt; &lt;isbn&gt;0743416910&lt;/isbn&gt; &lt;price&gt;5.99&lt;/price&gt; &lt;/book&gt; &lt;book year="1995"&gt; &lt;title&gt;Zodiac&lt;/title&gt; &lt;author&gt;Neal Stephenson&lt;/author&gt; &lt;publisher&gt;Spectra&lt;/publisher&gt; &lt;isbn&gt;0553573862&lt;/isbn&gt; &lt;price&gt;7.50&lt;/price&gt; &lt;/book&gt; &lt;!-- more books... --&gt; &lt;/inventory&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload