tags:

views:

53

answers:

1

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.

+2  A: 

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));
Elisha
Thanks Elisha. This looks close to what I need. Will try it out later. BTW, I'm working with pythons lxml so will have to adapt this a bit.
Rasputin Jones