views:

72

answers:

1

I've tried reading various tutorials online but I can't make any headway on solving this issue which is easy to describe but which I can not conceive of a solution.

Here is some sample XML:

<AAA>
    <BBB>
        <CCC>1</CCC>
        <CCC>2</CCC>
    </BBB>
    <BBB>
        <CCC>3</CCC>
        <CCC>4</CCC>
    </BBB>
</AAA>

I want to be able to select the last <CCC> in each container... in other words I want to be able to pull <CCC>2</CCC> and <CCC>4</CCC>. I've tried countless expressions to achieve this end but the best I can do is to get the very last <CCC> (which contains 4).

It seems like //BBB/CCC[last()] should work but it apparently selects all the CCC's that are children of BBB (4 total), and only then does it process the last() predicate - and therefor only returns a single element <CCC>4</CCC>

This is driving me nuts! Can anyone show me the light? Many thanks!!

+5  A: 
/AAA/BBB/CCC[position() = last()]

//BBB/CCC[position() = last()] and //CCC[position() = last()] also seem to work. I found a cool site for xpath testing here: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm

Ryan Cook
Nice! Thanks for sharing the website link :)
Carlos Lima
Shorter (but equivalent): `/AAA/BBB/CCC[last()]` or `//CCC[last()]`. Note: Whenever possible, I would avoid the `//` shorthand, as it is comparatively expensive. Even something like `/*/*/CCC[last()]` is better than `//`.
Tomalak