title: How to extract element value from an xml containing namespaces with xPath in Java?
body: <p><strong>Environment:</strong> Windows 10, Eclipse, Java 1.5</p>
  
  <p><strong>Objective:</strong>
  I'm trying to obtain the element text value of an xml using xPath. The xml contains various namespaces.</p>
  
  <p><strong>Problem:</strong> I always get an empty value.</p>
  
  <p>I checked out a few threads on SO but nothing worked. The xml absolute path opens fine on the browser.</p>
  
  <p>This is what I have:</p>
  
  <pre><code>//Initialize objects
  DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = null;
  builderFactory.setNamespaceAware(true);
  builder = builderFactory.newDocumentBuilder();
  Document xmlDocument = builder.parse(xmlFINAL);//File with absolute path
  XPath xPath = (XPath) XPathFactory.newInstance().newXPath();  
  
  //NamespaceContext used for xPath
  NamespaceContext nsContext = new NamespaceContext (){
  public String getNamespaceURI(String prefix) {
                   if (prefix == null) {            
                          throw new NullPointerException("Null prefix");
                    } else if ("ns2".equals(prefix)) {            
                          return "http://ns2";
                    }else{
                        return "http://ns1";
                    }
  
              }
  
              public String getPrefix(String namespaceURI) {
                  return null;
              }
  
              public Iterator getPrefixes(String namespaceURI) {
                  return null;
              }
  
          };
  xPath.setNamespaceContext(nsContext);
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/iBkcs.png" rel="nofollow noreferrer">This is a part of the Document content</a></p>
  
  <p>Test xml (mine is too big):</p>
  
  <pre><code>&lt;root_element xmlns="http://ns1" xmlns:ns2="http://ns2"&gt;
      &lt;element1&gt;
      ...
          &lt;ns2:element2&gt;
              &lt;ns2:element3&gt;I want this text&lt;/element3&gt;
          &lt;/element2&gt;
      ...
      &lt;/element1&gt;
  &lt;/root_element &gt;
  </code></pre>
  
  <p>Getting element value (which returns always <code>""</code>):</p>
  
  <pre><code>String expression = "/root_element/element1/ns2:element2/ns2:element3/text()";
  String valor = (String) xPath.compile(expression).evaluate(xmlDocument,XPathConstants.STRING);
  //or
  String valor = xPath.evaluate(expression, xmlDocument);
  </code></pre>