使用默认名称空间(无前缀)的文档的XPath处理与使用前缀的文档的XPath处理相同:
对于命名空间合格的文档,可以在执行XPath时使用NamespaceContext。你将需要在XPath中为片段添加前缀以匹配NamespaceContext。你使用的前缀不需要与文档中使用的前缀匹配。
http://download.oracle.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html
这是你的代码的外观:
import java.util.Iterator;import javax.xml.namespace.NamespaceContext;import javax.xml.parsers.documentBuilder;import javax.xml.parsers.documentBuilderFactory;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathFactory;import org.w3c.dom.document;import org.w3c.dom.NodeList;public class Demo { public static void main(String[] args) { documentBuilderFactory domFactory = documentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); try { documentBuilder builder = domFactory.newdocumentBuilder(); document dDoc = builder.parse("E:/test.xml"); XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(new MyNamespaceContext()); NodeList nl = (NodeList) xPath.evaluate("/ns:root/ns:author", dDoc, XPathConstants.NODESET); System.out.println(nl.getLength()); } catch (Exception e) { e.printStackTrace(); } } private static class MyNamespaceContext implements NamespaceContext { public String getNamespaceURI(String prefix) { if("ns".equals(prefix)) { return "http://www.mydomain.com/schema"; } return null; } public String getPrefix(String namespaceURI) { return null; } public Iterator getPrefixes(String namespaceURI) { return null; } }}
注意:我还使用了Dennis建议的更正的XPath 。
以下内容似乎也可行,并且更接近你的原始问题:
import javax.xml.parsers.documentBuilder;import javax.xml.parsers.documentBuilderFactory;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathFactory;import org.w3c.dom.document;import org.w3c.dom.NodeList;public class Demo { public static void main(String[] args) { documentBuilderFactory domFactory = documentBuilderFactory.newInstance(); try { documentBuilder builder = domFactory.newdocumentBuilder(); document dDoc = builder.parse("E:/test.xml"); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nl = (NodeList) xPath.evaluate("/root/author", dDoc, XPathConstants.NODESET); System.out.println(nl.getLength()); } catch (Exception e) { e.printStackTrace(); } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)