2008-12-04 81 views
8

我有一個類似的結構的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

回答

18

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

我相信這個XPath表達式是「//category/subCategoryList/category」。如果您只想要根節點category的子節點(假設它是文檔根節點),請嘗試「/category/subCategoryList/category」。

0

這會爲你工作:

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

然後如你所願,你可以解析類的孩子。