用Java中的XPath解析XML

用Java中的XPath解析XML,java,xml,xpath,Java,Xml,Xpath,我有一个结构类似于以下内容的XML: <category> <subCategoryList> <category> </category> <category> <!--and so on --> </category> </subCategoryList> </category> 我有一个Catego

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

<category>
   <subCategoryList>
      <category>

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

我有一个Category类,它有一个
子类别
列表(
列表
)。我试图用XPath解析这个XML文件,但我无法获取类别的子类别


如何使用XPath实现这一点?有更好的方法吗?

我认为XPath表达式应该是“
//category/subcategory list/category
”。如果只需要根
类别
节点的子节点(假设它是文档根节点),请尝试“
/category/subcategory列表/category

这将对您有用:

NodeList nodes = (NodeList) xpath.evaluate("//category//subCategoryList/category",
inputSource, XPathConstants.NODESET);
然后,您可以根据需要解析category的子类。

提供了您所需的一切。短裤:

 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()); 
    }
  }
publicstaticvoidmain(字符串[]args)
抛出ParserConfiguration异常、SAXException、,
IOException,XPathExpressionException{
DocumentBuilderFactory domFactory=
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder=domFactory.newDocumentBuilder();
documentdoc=builder.parse(“persons.xml”);
XPath=XPathFactory.newInstance().newXPath();
//用于显示所有节点值的XPath查询
XPathExpression expr=xpath.compile(“//person/*/text()”);
Object result=expr.evaluate(doc,XPathConstants.NODESET);
节点列表节点=(节点列表)结果;
对于(int i=0;i
是,但这会返回一个与该表达式匹配的所有节点的列表,因此所有子节点都包含在内。。。谢谢你说所有的孩子都包括在内是什么意思?我想你漏掉了一些细节。什么是“等等”…这很重要,问题是你的文件有多大。