title: Why doesn't XPath namespace-uri() work out of the box with Java?
body: <p>I am trying to use the <code>namespace-uri()</code> function in XPath to retrieve nodes based on their fully qualified name. The query <code>//*[local-name() = 'customerName' and namespace-uri() = 'http://example.com/officeN']</code> in <a href="http://www.xmlme.com/XpathTool.aspx" rel="nofollow">this online XPath tester</a>, among others, correctly returns the relevant nodes. Yet the following self-contained Java class does not retrieve anything. What am I doing wrong with <code>namespace-uri()</code>?</p>
  
  <pre><code>import java.io.StringReader;
  
  import javax.xml.parsers.DocumentBuilderFactory;
  import javax.xml.xpath.XPathConstants;
  import javax.xml.xpath.XPathExpression;
  import javax.xml.xpath.XPathFactory;
  
  import org.w3c.dom.Document;
  import org.w3c.dom.NodeList;
  import org.xml.sax.InputSource;
  public class Test{
      public static void main(String[] args)throws Exception {
  
          XPathExpression expr = XPathFactory.newInstance().newXPath().compile(
                  "//*[local-name() = 'customerName' and namespace-uri() = 'http://example.com/officeN']");
          String xml=
              "&lt;Agents xmlns:n=\"http://example.com/officeN\"&gt;\n"+
              "\t&lt;n:Agent&gt;\n\t\t&lt;n:customerName&gt;Joe Shmo&lt;/n:customerName&gt;\n\t&lt;/n:Agent&gt;\n"+
              "\t&lt;n:Agent&gt;\n\t\t&lt;n:customerName&gt;Mary Brown&lt;/n:customerName&gt;\n\t&lt;/n:Agent&gt;\n&lt;/Agents&gt;";
          System.out.println(xml);
          Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
          NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
          System.err.println("\n\nNodes:");
          for (int i = 0; i &lt; nodes.getLength(); i++) {
              System.err.println(nodes.item(i));
  
          }
      }
  }
  </code></pre>