当前位置:  开发笔记 > 编程语言 > 正文

使用Java中的XPath解析XML

如何解决《使用Java中的XPath解析XML》经验,为你挑选了1个好方法。

我有一个XML结构与此类似:


   
      

      
      
         
      
   

我有一个具有subcategorylist(List)的Category类.我正在尝试使用XPath解析此XML文件,但我无法获取类别的子类别.

我怎么能用XPath做到这一点?有一个更好的方法吗?



1> ripper234..:

此链接包含您需要的一切.简而言之:

 public static void main(String[] args) 
   throws ParserConfigurationException, SAXException, 
          IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = 
    DocumentBuilderFactory.newInstance();
          domFactory.setNamespaceAware(true); 
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("persons.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
       // XPath Query for showing all nodes value
    XPathExpression expr = xpath.compile("//person/*/text()");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
     System.out.println(nodes.item(i).getNodeValue()); 
    }
  }

推荐阅读
pan2502851807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有