使用Java中的XPath解析XML

Mg.*_*Mg. 9 java xml xpath

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

<category>
   <subCategoryList>
      <category>

      </category>
      <category>
         <!--and so on -->
      </category>
   </subCategoryList>
</category>
Run Code Online (Sandbox Code Playgroud)

我有一个具有subcategorylist(List<Category>)的Category类.我正在尝试使用XPath解析此XML文件,但我无法获取类别的子类别.

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

rip*_*234 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()); 
    }
  }
Run Code Online (Sandbox Code Playgroud)