使用xpath匹配第一组元素

时间:2010-03-26 18:05:30

标签: python xpath lxml

我有一个看起来像这样的xml文档。

<foo>
    <bar type="artist"/> Bob Marley </bar>
    <bar type="artist"/> Peter Tosh </bar>
    <bar type="artist"/> Marlon Wayans </bar>
</foo>
<foo>
    <bar type="artist"/> Bob Marley </bar>
    <bar type="artist"/> Peter Tosh </bar>
    <bar type="artist"/> Marlon Wayans </bar>
</foo>
<foo>
    <bar type="artist"/> Bob Marley </bar>
    <bar type="artist"/> Peter Tosh </bar>
    <bar type="artist"/> Marlon Wayans </bar>
</foo>

我想构建一个只返回第一个集合的xpath:

<bar type="artist"/> Bob Marley </a>
<bar type="artist"/> Peter Tosh </a>
<bar type="artist"/> Marlon Wayans </a>

怎么会这样呢?我试过//bar[@type='artist'],但显而易见的还有更多。提前谢谢。

1 个答案:

答案 0 :(得分:2)

为了只获取某些“索引”节点的子元素:

//foo[1]/bar[@type='artist']

C#中的例子:

string xml =
    @"<root>
        <foo>
            <bar type='artist'> Artist 1 </bar>
            <bar type='artist'> Artist 2 </bar>
            <bar type='artist'> Artist 3 </bar>
        </foo>
        <foo>
            <bar type='artist'> Artist 1 </bar>
            <bar type='artist'> Artist 2 </bar>
            <bar type='artist'> Artist 3 </bar>
            <bar type='artist'> Artist 4 </bar>
        </foo>
    </root>";
XmlDocument document = new XmlDocument();
document.LoadXml(xml);

Assert.That(document.SelectNodes(@"/root/foo[1]/bar[@type='artist']").Count,
                                 Is.EqualTo(3));
Assert.That(document.SelectNodes(@"//foo[1]/bar[@type='artist']").Count,
                                 Is.EqualTo(3));