在Java中使用XPath解析XML

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

         

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

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

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

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

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

这对你有用:

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

然后,您可以根据需要解析类别的子项。