views:

663

answers:

2

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?

+7  A: 

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

Marc Gravell
I meant the latter. Thanks.
izb
+5  A: 
"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"
Tomalak
beat me to it :) +1 for the explanation
annakata
Ah, of course :) Pesky array-like notation...
izb