XPath returns null for xml with defaultNamespace

I believe that it worked some time ago, but now xpath returns null. Can someone help me find my stupid mistake in the following code? Or will I have to provide a 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(); } 

The XML document is here:

 <?xml version="1.0" encoding="UTF-8"?> <root xmlns="http://www.example.com/schema"> <class /> <class /> </root> 
+3
source share
1 answer

Three options are possible. In order, the easiest thing from my point of view is:

  • change XPath from "//class" to "//*[local-name() = 'class']" . This is a bit kludgy, but it will ignore namespaces. If this still gives you zero, you know that the problem is not namespaces.
  • register the namespace prefix for "http://www.example.com/schema" in your Java code and use it in the XPath expression: "//foo:class"
  • find out which parser implementation you use and why it behaves differently than @ Rodney, or change it to another.
+5
source

Source: https://habr.com/ru/post/893152/


All Articles