title: Java evaluate XPath against a org.w3c.dom.Node
body: <p>Dipping my toe in a little Java at the minute and have a question about XPath.</p>
  
  <p>I have a large Xml and I want to use XPath to be able to grab a specific node and then fire further XPath calls against this small chunk of Xml.</p>
  
  <p>Here s rough outline of my Xml:</p>
  
  <pre><code>&lt;Page&gt;
    &lt;ComponentPresentations&gt;
      &lt;ComponentPresentation&gt;
        &lt;Component&gt;
          &lt;Title&gt;
        &lt;ComponentTemplate&gt; 
      &lt;ComponentPresentation&gt;
        &lt;Component&gt;
          &lt;Title&gt;
        &lt;ComponentTemplate&gt; 
  </code></pre>
  
  <p>My first XPath selects the <code>&lt;Component&gt;</code> node based upon the value of a <code>&lt;ComponenTemplate&gt;</code> Id value:</p>
  
  <pre><code>String componentExpFormat = "/Page/ComponentPresentations/ComponentPresentation/ComponentTemplate/Id[text()='%1$s']/ancestor::ComponentPresentation";
  String componentExp = String.format(componentExpFormat, template);
  XPathExpression expComponent = xPath.compile(componentExp);
  Node componentXml = (Node) expComponent.evaluate(xmldoc, XPathConstants.NODE);
  </code></pre>
  
  <p>This gives me the <code>&lt;Component&gt;</code> I want but I can;t seem to be able to then XPath against the Node:</p>
  
  <pre><code>String componentExpTitle = "/Component/Fields/item/value/Field/Name[text()='title']/parent::node()/Values/string";                                  
  XPathExpression expTitle = xPath.compile(componentExpTitle);
  String eventName = expTitle.evaluate(componentXml, XPathConstants.STRING).toString();
  </code></pre>
  
  <p>Without this I'll have to include the full XPath each time:</p>
  
  <pre><code>/Page/ComponentPresentations/ComponentPresentation/ComponentTemplate/Id[text()='%1$s']/ancestor::ComponentPresentation/Component/Fields/item/value/Field/Name[text()='title']/parent::node()/Values/string
  </code></pre>
  
  <p>Is that the only way?</p>
  
  <p>Cheers</p>