Blankman
Blankman

Reputation: 267320

How can I use XPath to get elements?

My XML is like:

<root>
  <section name="blah">
    <item name="asdf">2222</item>
  </section>
</root>

I will have multiple 'sections' in the XML, I want to fetch a particular section.

In this case, I need to get items that are in the section named "blah".

Upvotes: 1

Views: 420

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064204

The xpath is then:

/root/section[@name='blah']/item

for example, in XmlDocument:

foreach(XmlElement item in doc.SelectNodes("/root/section[@name='blah']/item"))
{
     Console.WriteLine(item.GetAttribute("name"));
     Console.WriteLine(item.InnerText);
}

Edit re comments: if you just want the sections, then use:

/root/section[@name='blah']

but then you'll need to iterate the data manually (since you can theoretically have multiple sections named "blah", each of which can have multiple items).

Upvotes: 4

Related Questions