title: Looping over nodes and extracting specific subnode values using Java's XPath
body: <p>I understand from Googling that it makes more sense to extract data from XML using XPath than by using DOM looping.</p>
  
  <p>At the moment, I have implemented a solution using DOM, but the code is verbose, and it feels untidy and unmaintainable, so I would like to switch to a cleaner XPath solution.</p>
  
  <p>Let's say I have this structure:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;products&gt;
      &lt;product&gt;
          &lt;title&gt;Some title 1&lt;/title&gt;
          &lt;image&gt;Some image 1&lt;/image&gt;
      &lt;/product&gt;
      &lt;product&gt;
          &lt;title&gt;Some title 2&lt;/title&gt;
          &lt;image&gt;Some image 2&lt;/image&gt;
      &lt;/product&gt;
      ...
  &lt;/products&gt;
  </code></pre>
  
  <p>I want to be able to run a for loop for each of the <code>&lt;product&gt;</code> elements, and inside this for loop, extract the title and image node values.</p>
  
  <p>My code looks like this:</p>
  
  <pre><code>InputStream is = conn.getInputStream();          
  DocumentBuilder builder =
    DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc = builder.parse(is);
  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  XPathExpression expr = xpath.compile("/products/product");
  Object result = expr.evaluate(doc, XPathConstants.NODESET);
  NodeList products = (NodeList) result;
  for (int i = 0; i &lt; products.getLength(); i++) {
      Node n = products.item(i);
      if (n != null &amp;&amp; n.getNodeType() == Node.ELEMENT_NODE) {
          Element product = (Element) n;
          // do some DOM navigation to get the title and image
      }
  }
  </code></pre>
  
  <p>Inside my <code>for</code> loop I get each <code>&lt;product&gt;</code> as a <code>Node</code>, which is cast to an <code>Element</code>.</p>
  
  <p>Can I simply use my instance of <code>XPathExpression</code> to compile and run another <code>XPath</code> on the <code>Node</code> or the <code>Element</code>?</p>