Prabu
Prabu

Reputation: 3728

xpath getting multiple node values - xml parser using java

below are the xml file

<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>

my expected conditions:

1.How can i getting all the node value (i.e FD0297663, 20070403 and FD0745459P,20060424)

2.its may be single (i.e Priority -claim tag) or more than a single level is possible

my existing code getting first level value only

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

Upvotes: 0

Views: 932

Answers (1)

rapha&#235;λ
rapha&#235;λ

Reputation: 6523

Below is a working example:

  • updated the xpath expressions (e.g, /priority-claims/priority-claim/document-id/doc-number/text())
  • using 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());
    }
    

Here is a linkt to a gist with a runnable version: https://gist.github.com/rparree/1c7eb8e9ca928b98418fdb167a2096a3

Upvotes: 2

Related Questions