24

I have XML like this:

<AAA>
    <BBB aaa="111" bbb="222">
        <CCC/>
        <CCC xxx="555" yyy="666" zzz="777"/>
    </BBB>
    <BBB aaa="999">
        <CCC xxx="qq"/>
        <DDD xxx="ww"/>
        <EEE xxx="oo"/>
    </BBB>
    <BBB>
        <DDD xxx="oo"/>
    </BBB>
</AAA>

I want to get first <CCC> element. But with XPath expression //*/CCC[1] I have got two <CCC> elements. Each of them is the first elemet in <BBB></BBB> context. How to get first element in subset?

Stas
  • 243
  • 1
  • 2
  • 4
  • 1
    Good question, +1. See my answer for a complete, short and easy one-liner XPath expression that selects exactly the wanted element. :) – Dimitre Novatchev Apr 11 '11 at 13:00
  • possible duplicate of [Select first instance only with XPath?](http://stackoverflow.com/questions/453191/select-first-instance-only-with-xpath) –  Apr 11 '11 at 16:36
  • Great question. Actually did a [blog post](http://generalredneck.com/blog/xpath-conditionals-subsets) on this recently! – General Redneck Oct 23 '12 at 22:13

2 Answers2

42

This one should work for you:

(//*/CCC)[1]
Lasse Espeholt
  • 17,092
  • 5
  • 57
  • 97
15

I want to get first element. But with XPath expression //*/CCC[1] I have got two elements. Each of them is the first elemet in <BBB></BBB> context. How to get first element in subset?

This is a FAQ:

The [] operator has a higher precedence (binds stronger) than the // abbreviation.

Use:

(//CCC)[1]

This selects the first (in document order) CCC element in the XML document.

Dimitre Novatchev
  • 230,371
  • 26
  • 281
  • 409
  • So, what is it that causes that problem? – Dimitre Novatchev Jul 14 '13 at 21:10
  • @Priti, This is a *rule*, saying that CDATA is only a lexical representation of a (part of) the value of a text node. And this has nothing to do with the current question/answer. If you had got any useful XPath book, you wouldn't be asking such basic questions. Or if you ask this as a proper SO question, then many people would answer promptly. – Dimitre Novatchev Jul 14 '13 at 21:39
  • @Priti, I explain this here: http://stackoverflow.com/questions/4007413/xpath-query-to-get-nth-instance-of-an-element/4008925#4008925 – Dimitre Novatchev Jul 15 '13 at 14:12
  • 1
    @Priti, This happens when you have specified `` the characters will be unescaped. – Dimitre Novatchev Jul 15 '13 at 14:32
  • Here is my [`question`](http://stackoverflow.com/questions/17657003/need-to-understand-why-cdata-section-is-treated-as-if-the-cdata-and). – Arup Rakshit Jul 15 '13 at 14:43
  • Thanks .. I was waiting for you,hoping that you would add anything more with that. As you approved,I am going to mark it as accepted answer. – Arup Rakshit Jul 16 '13 at 09:09