以下是xml文件

<priority-claims>
          <priority-claim sequence="1" kind="national">
            <document-id document-id-type="maindoc">
             <doc-number>FD0297663</doc-number>
             <date>20070403</date>
            </document-id>
          </priority-claim>
          <priority-claim sequence="2" kind="national">
            <document-id document-id-type="maindoc">
              <doc-number>FD0745459P</doc-number>
              <date>20060424</date>
            </document-id>
            </priority-claim>
</priority-claims>


我的预期条件:

1,如何获取所有节点值(即FD0297663, 20070403 and FD0745459P,20060424

2.它可以是单个(即优先声明标签),也可以是多个级别

我现有的代码仅获得一级价值

String priorityNumber = xPath.compile("//priority-claim//doc-number").evaluate(xmlDocument);
 String priorityDate = xPath.compile("//priority-claim//date").evaluate(xmlDocument);

最佳答案

下面是一个工作示例:


更新了xpath表达式(例如/priority-claims/priority-claim/document-id/doc-number/text()
使用NodeList

NodeList priorityNumbers = (NodeList) xPath.compile("/priority-claims/priority-claim/document-id/doc-number/text()").evaluate(xmlDocument, XPathConstants.NODESET);
NodeList priorityDates = (NodeList) xPath.compile("/priority-claims/priority-claim/document-id/date/text()").evaluate(xmlDocument,XPathConstants.NODESET);

for(int i=0; i<priorityNumbers.getLength();i++){
    System.out.println(priorityNumbers.item(i).getNodeValue());
}

for(int i=0; i<priorityDates.getLength();i++){
    System.out.println(priorityDates.item(i).getNodeValue());
}



这是带有可运行版本的要点的链接:https://gist.github.com/rparree/1c7eb8e9ca928b98418fdb167a2096a3

10-08 18:45