Monday, April 25, 2011

How to select the nth item in xpath 1.0?

I have some XML and an XPath query. I'm using Yahoo! widgets, so I'm using XPath 1.0.

Here's the gist of my XML...

<root>
    <cat num="SOURCE">
        <movie>
            <swf>speak.swf</swf> 
            <width>250</width> 
            <height>150</height> 
            <colour>cccccc</colour> 
        </movie>
        <movie>
            <swf>inertia.swf</swf> 
            <width>380</width> 
            <height>130</height> 
            <colour>9a9a9a</colour> 
        </movie>
        <movie>
            <swf>swing.swf</swf> 
            <width>380</width> 
            <height>130</height> 
            <colour>9A9A9A</colour> 
        </movie>
        ....

Now... if I run this query:

"root/cat/movie/swf"

I get 42 results, all 'swf' nodes which is correct.

If however, I just want the 6th one, I'd like to be able to do:

"root/cat/movie/swf[6]"

But I get a list containing 0 nodes.

Weirdly, using [1] (And no other value) yields my list of all 42 nodes.

Clearly I'm missing something quite fundamental here. Anyone see what it is?

From stackoverflow
  • I wonder if you mean:

    "root/cat/movie[6]/swf"
    

    (gets the swf of the 6th movie)

    or alternatively:

    "(root/cat/movie/swf)[6]"
    

    (finds all the movie/swf elements, and selects the 6th)

    When each movie has exactly one swf, the two are the same; if a movie has zero or multiple swf elements, they the two queries are subtly different...

    izb : I meant the latter. Thanks.
  • "root/cat/movie/swf[6]"
    

    refers to each 6th <swf> node in "root/cat/movie" context.

    You have only one <swf> node each.

    What you mean is:

    "root/cat/movie[6]/swf"
    
    annakata : beat me to it :) +1 for the explanation
    izb : Ah, of course :) Pesky array-like notation...

0 comments:

Post a Comment