2

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

1
  • Your question could do with a tweak or two - the XML endtag is wrong and the sample xpath says "b" instead of d. Good answer below, though, I learnt something today ;] Commented Feb 2, 2012 at 9:23

1 Answer 1

5

Use:

//a/b/c[@type='lol'][2]/d/text()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , i found the solution myself too.. just now.. I came to add my solution , u(@ Kirill) had already put the solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.