1

我有一个看起来像这样的 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'],但很明显还有更多。提前致谢。

4

1 回答 1

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));
于 2010-03-26T18:09:28.933 回答