Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 671
izb Avatar asked Mar 18 '09 11:03

izb


People also ask

What is the meaning of '/' in Xpath?

Single Slash “/” – Single slash is used to create Xpath with absolute path i.e. the xpath would be created to start selection from the document node/start node.


1 Answers

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

like image 112
Marc Gravell Avatar answered Sep 27 '22 19:09

Marc Gravell