9

我有一个类似于以下结构的 XML:

<category>
   <subCategoryList>
      <category>

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

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

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

4

3 回答 3

19

这个链接有你需要的一切。简而言之:

 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()); 
    }
  }
于 2010-05-12T11:18:43.340 回答
2

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

于 2008-12-04T14:52:19.063 回答
0

这将为您工作:

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

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

于 2008-12-04T14:52:37.143 回答