3

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>
WSK
  • 5,949
  • 8
  • 49
  • 74
  • When I run this (with Java 1.6) it prints out "2". – Rodney Gitzel Dec 07 '10 at 18:15
  • 1
    The variable here is the default parser implementation selected by `domFactory.newDocumentBuilder().parse(file)`. – Jim Garrison Dec 07 '10 at 20:11
  • Oh God, it is making me mad. I am also testing under java 1.6 but getting 0. Can you give me some idea what should I check? – WSK Dec 07 '10 at 20:21
  • Sorry @Jim, I could not get your point. If you are talking about "file" variable, I edited it to a fixed value for clarity please explain a bit, otherwise – WSK Dec 07 '10 at 20:26
  • 2
    You could be instantiating a different DocumentBuilderFactory and different parser than Rodney, and getting different results. This can occur if you have several parser implementations on your classpath and/or the JDK is configured to use a specific parser. Look at the javadoc for DocumentBuilderFactory to find out how to control which parser is used, and also learn about the jaxp.debug option, which will help you find out what's happening. – Jim Garrison Dec 07 '10 at 20:34
  • 4
    @Leslie Norman: **There is a default namespace declaration in your input sample. You need to register a prefix-namespace URI binding for your XPath expression**. That makes this a duplicate question of many... –  Dec 07 '10 at 21:00
  • Thank you guys for your valuable suggestions and comments. I helped me to understand my problem and its solution – WSK Dec 09 '10 at 03:54

1 Answers1

5

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
LarsH
  • 27,481
  • 8
  • 94
  • 152