title: XPath getting a sequence of element tags (Java / Saxon)
body: <p>I am using <strong>Java</strong> with <strong>Saxon HE 9.4</strong> so I can have <strong>XPath 2.0</strong> support.</p>
  
  <p>Given the following XML instance document:</p>
  
  <pre><code>&lt;entities&gt;
      &lt;entity&gt;
          &lt;person&gt;
              James
          &lt;/person&gt;
      &lt;/entity&gt;
      &lt;entity&gt;
          &lt;legalEntity&gt;
              ACME
          &lt;/legalEntity&gt;
      &lt;/entity&gt;
  &lt;/entities&gt;
  </code></pre>
  
  <p>I know I can get a list of the entity element tags by doing a:</p>
  
  <pre><code>XPathExpression expr = xpath.compile("/entities/entity/*");
  NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
  for (int i = 0 ; i &lt; nodes.getLength() ; i++)
      System.out.println("element name = "+ nodes.item(i).getNodeName());
  </code></pre>
  
  <p>The above will output:</p>
  
  <pre><code>element name = person
  element name = legalEntity
  </code></pre>
  
  <p>... as expected.</p>
  
  <p>However, the logic is spread in two places: the XPath expression itself, and the call to <code>getNodeName</code> method. What I would like is an XPath expression that would return a generic list of results, which I could iterate over by calling some generic method (not <code>getNodeName</code>).</p>
  
  <p>This way, all the logic could reside in the XPath expression itself and my code could just keep the XPath strings in a file and process them at runtime to get lists of results.</p>
  
  <p>Trying the XPAth expression <code>/entities/entity/*/name()</code> only fetches the first value (person):</p>
  
  <pre><code>XPathExpression expr = xpath.compile("/entities/entity/*/name()");
  System.out.println("element name = "+expr.evaluate(doc));
  </code></pre>
  
  <p>... and the code breaks at runtime if I try to cast that to a <code>NodeList</code>:</p>
  
  <pre><code>XPathExpression expr = xpath.compile("/entities/entity/*/name()");
  NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
  for (int i = 0 ; i &lt; nodes.getLength() ; i++) {
      ...
  </code></pre>
  
  <p>(the above fails with: <code>net.sf.saxon.trans.XPathException: Cannot convert XPath value to Java object: required class is org.w3c.dom.NodeList; supplied value has type xs:string</code>)</p>
  
  <p>So is there a generic way to get <strong>XPath</strong> expressions evaluate to list of results (which could be element tags, element values, attribute values and tags, etc.) so that the code iterating over these results is the same in all cases and doesn't have to differentiate between calls to <code>getNodeName()</code> or <code>getNodeValue()</code> ?</p>