开发者

Matching first set of elements with xpath

I have an xml document that looks like this.

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

I would like to construct an xpath that returns only the first set:

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

How would one go about this? I have tried //bar[@type='artist'] but it's obvious there's more to this. Thanks in advance.


In order to get only sub elements of some "indexed" node:

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

Exmaple in 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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜