Search code examples
javascriptxmlxpathyahoo-widgetsxpath-1.0

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?


Solution

  • 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...