title: Parse XML using namespace prefixes in syntax for root elements - Java
body: <p>I have an <code>XML</code> of the form:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;semseg:Envelope xmlns:semseg="http://a-random-URL" xmlns="http://another-random-URL"&gt;
      &lt;semseg:subject&gt;Subject&lt;/semseg:subject&gt;
      &lt;semseg:Sender&gt;
          &lt;semseg:name&gt;Me&lt;/semseg:name&gt;
      &lt;/semseg:Sender&gt;
      &lt;Triangle&gt;
          &lt;Triangle time='2017-11-29'&gt;
              &lt;Triangle key='a' value='b'/&gt;
              &lt;Triangle key='c' value='d'/&gt;
              &lt;Triangle key='e' value='f'/&gt;
              &lt;Triangle key='g' value='h'/&gt;
          &lt;/Triangle&gt;
      &lt;/Triangle&gt;
  &lt;/semseg:Envelope&gt;
  </code></pre>
  
  <p>And I am trying to retrieve the element <code>&lt;Triangle&gt;</code> (<em>not</em> <code>&lt;Triangle time='2017-11-29'&gt;</code> - element names are a bit repetitive in this XML) using <code>XPath</code>. Part of the code is the following:</p>
  
  <pre><code>DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  documentBuilderFactory.setNamespaceAware(true);
  DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
  Document doc = documentBuilder.parse("file.xml");
  
  XPathFactory xPathFactory = XPathFactory.newInstance();
  XPath xPath = xPathFactory.newXPath();
  XPathExpression xpr = xPath.compile("/semseg:Envelope/Triangle");
  NodeList nodes = (NodeList)xpr.evaluate(doc, XPathConstants.NODESET);
  </code></pre>
  
  <p>I have tried many possible combinations for the <code>XPath</code> without any luck unfortunately since no elements are selected. Nevertheless, testing the same <code>XPath</code> with <a href="https://www.freeformatter.com/xpath-tester.html#ad-output" rel="nofollow noreferrer">this</a> online <code>XPath</code> checker and the same <code>XML</code> file yields exactly the results I am looking for. It evens works for attribute retrieval using XPaths like </p>
  
  <pre><code>/semseg:Envelope/Triangle/Triangle/@time
  </code></pre>
  
  <p>Seems like there is a problem with the namespace prefixes. Parsing <code>XML</code>s without any namespace prefixes works just fine with <code>XPath</code>.</p>