使用Xpath查询xml文档节点数据

前端之家收集整理的这篇文章主要介绍了使用Xpath查询xml文档节点数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

清单 4. 用固定的 XPath 表达式查询 XML 文档的完整程序

 
 
  1. importjava.io.IOException;
  2. importorg.w3c.dom.*;
  3. importorg.xml.sax.SAXException;
  4. importjavax.xml.parsers.*;
  5. importjavax.xml.xpath.*;
  6. publicclassXPathExample{
  7. publicstaticvoidmain(String[]args)
  8. throwsParserConfigurationException,SAXException,
  9. IOException,XPathExpressionException{
  10. DocumentBuilderFactorydomFactory=DocumentBuilderFactory.newInstance();
  11. domFactory.setNamespaceAware(true);//neverforgetthis!
  12. DocumentBuilderbuilder=domFactory.newDocumentBuilder();
  13. Documentdoc=builder.parse("books.xml");
  14. XPathFactoryfactory=XPathFactory.newInstance();
  15. XPathxpath=factory.newXPath();
  16. XPathExpressionexpr
  17. =xpath.compile("//book[author='NealStephenson']/title/text()");
  18. Objectresult=expr.evaluate(doc,XPathConstants.NODESET);
  19. NodeListnodes=(NodeList)result;
  20. for(inti=0;i<nodes.getLength();i++){
  21. System.out.println(nodes.item(i).getNodeValue());
  22. }
  23. }
  24. }
原文链接:https://www.f2er.com/xml/298986.html

猜你在找的XML相关文章