使用XPath解析XML在Java中

问题描述:

我有一个类似的结构的XML:使用XPath解析XML在Java中

<category> 
    <subCategoryList> 
     <category> 

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

我有一个具有subcategory列表(List<Category>)类别类。我试图用XPath解析这个XML文件,但我无法获得某个类别的子类别。

如何使用XPath执行此操作?有一个更好的方法吗?

+0

什么是“等等”...这很重要 – tcurdt 2008-12-05 01:50:20

+0

另外问题是你的文件有多大。 – tcurdt 2008-12-05 01:51:30

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

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

这会为你工作:

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

然后如你所愿,你可以解析类的孩子。