Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

java - XPath is returning null for xml with defaultNamespace

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...