在 Java 中使用 XPath 解析 XML [重复]

Posted

技术标签:

【中文标题】在 Java 中使用 XPath 解析 XML [重复]【英文标题】:Parsing XML with XPath in Java [duplicate] 【发布时间】:2010-09-25 08:13:42 【问题描述】:

我有一个类似这样结构的 XML:

<category>
   <subCategoryList>
      <category>

      </category>
      <category>
         <!--and so on -->
      </category>
   </subCategoryList>
</category>

我有一个具有subcategory 列表(List&lt;Category&gt;)的类别类。我正在尝试使用 XPath 解析此 XML 文件,但我无法获取某个类别的子类别。

如何使用 XPath 做到这一点?有没有更好的方法来做到这一点?

【问题讨论】:

什么是“等等”……这很重要 还有一个问题是你的文件有多大。 【参考方案1】:

我相信 XPath 表达式将是“//category/subCategoryList/category”。如果您只想要根category 节点的子节点(假设它是文档根节点),请尝试“/category/subCategoryList/category”。

【讨论】:

是的,但这会返回一个与该表达式匹配的所有节点的列表,因此所有子节点都包括在内...谢谢 所有孩子都包括在内是什么意思?我认为您遗漏了一些细节。【参考方案2】:

这对你有用:

NodeList nodes = (NodeList) xpath.evaluate("//category//subCategoryList/category",
inputSource, XPathConstants.NODESET);

然后你可以根据需要解析类别的孩子。

【讨论】:

【参考方案3】:

This link 拥有您所需的一切。简而言之:

 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()); 
    
  

【讨论】:

以上是关于在 Java 中使用 XPath 解析 XML [重复]的主要内容,如果未能解决你的问题,请参考以下文章

在 Java 中使用 XPath 解析 XML [重复]

Java DocumentBuilderFactory(javax.xml)通过XPath解析xml文件

Java解析XML汇总(DOM/SAX/JDOM/DOM4j/XPath)

使用 Java XPath 解析 XML 简单字符串

避免在 Java 中使用 XPath 重复实例化 InputSource

Java XML DOM解析(xPath)