tharani dharan
tharani dharan

Reputation: 425

Java Xpath query

How can I use Java Xpath to get the value of 2nd "c" tag d and f as 2

<a>
    <b>
        <c type="lol">
            <d>1</d>
            <f>2</f>
        </c>
        <c type="lol">
            <d>2</d>
            <f>2</f>
        </c>
            <c type="h">
            <d>v</d>
            <f>d</f>
        </c>
    </b>
</a>

 { 
    DocumentBuilderFactory dBFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dB = dBFactory.newDocumentBuilder();
  Document doc = dB.parse(url);     
  System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  XPathExpression expr=null;
  String text= null;
  expr= xpath.compile("//a/b/c[@type='lol']/d/text()");// this gets the first value
  text = (String) expr.evaluate(doc, XPathConstants.STRING);
     } 

How can I use Java Xpath to get the value of 2nd "c" tag d and f as 2

Upvotes: 2

Views: 932

Answers (1)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56202

Use:

//a/b/c[@type='lol'][2]/d/text()

Upvotes: 5

Related Questions