首页 文章

如何在xpath 1.0中选择第n项?

提问于
浏览
17

我有一些XML和XPath查询 . 我正在使用Yahoo!小部件,所以我使用的是XPath 1.0 .

这是我的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>
        ....

现在......如果我运行此查询:

"root/cat/movie/swf"

我得到42个结果,所有'swf'节点都是正确的 .

但是,如果我只想要第6个,我希望能够做到:

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

但我得到一个包含0个节点的列表 .

奇怪的是,使用[1](而没有其他值)会产生我所有42个节点的列表 .

显然,我在这里遗漏了一些非常重要的东西 . 有谁看到它是什么?

2 回答

  • 9

    我想知道你的意思是:

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

    (获得第6部电影的SWF)

    或者:

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

    (找到所有的movie / swf元素,并选择第6个)

    当每部电影只有一个swf时,两者是相同的;如果一部电影有零个或多个swf元素,那么这两个查询会略有不同......

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

    是指 "root/cat/movie" 上下文中的每个第6个 <swf> 节点 .

    每个只有一个 <swf> 节点 .

    你的意思是:

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

相关问题