25

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?

3
  • 1
    Good question, +1. See my answer for a complete, short and easy one-liner XPath expression that selects exactly the wanted element. :) Commented Apr 11, 2011 at 13:00
  • possible duplicate of Select first instance only with XPath? Commented Apr 11, 2011 at 16:36
  • Great question. Actually did a blog post on this recently! Commented Oct 23, 2012 at 22:13

2 Answers 2

44

This one should work for you:

(//*/CCC)[1] 
Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

So, what is it that causes that problem?
@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.
@Priti, I explain this here: stackoverflow.com/questions/4007413/…
@Priti, This happens when you have specified <xsl:output method="xml/> (which is the default output method). If you specify <xsl:output method="text"/> the characters will be unescaped.
Here is my question.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.