XPath is returning null for xml with defaultNamespace

java, xpath

Solution

Three options are apparent. In order of easiest first from my point of view:

- change your XPath from `"//class"` to `"//*[local-name() = 'class']"`. It's a little kludgy but it will ignore namespaces. If this still gives you zero, you know the problem is not namespaces.

- register a namespace prefix for "http://www.example.com/schema" in your Java code, and use it in your XPath expression: `"//foo:class"`

- figure out what parser implementation you're using and why it's behaving differently from @Rodney's, or change to a different one

Problem

I believe it was working sometime ago but now xpath is returning null. Can somebody help me find my stupid mistake in following code? Or I will have to provide NamespaceContext even after setNamespaceAware(false)? ``` DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(false); domFactory.setIgnoringComments(true); domFactory.setIgnoringElementContentWhitespace(true); try { Document doc = domFactory.newDocumentBuilder().parse(new File("E:/Temp/test.xml")); XPath xp = XPathFactory.newInstance().newXPath(); NodeList nl = (NodeList) xp.evaluate("//class", doc, XPathConstants.NODESET); System.out.println(nl.getLength()); }catch (Exception e){ e.printStackTrace(); } ``` XML document is here: ``` <?xml version="1.0" encoding="UTF-8"?> <root xmlns="http://www.example.com/schema"> <class /> <class /> </root> ```

Original source