tags:

views:

140

answers:

1

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

+4  A: 

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

Marc Gravell
wouldn't it be doc.SelectNodes("/root/section[@name='blah']") ??
Blankman
@Blankman: Not as long as you are interested in the *items* that are child of such a section.
Tomalak
indeed: <quote>get items that have a section name "blah".</quote>
Marc Gravell
no that would only return collection of sections. you said you wanted to get access to a collection of items that are children of that particular section.
Mister Lucky
What I am doing is iterating through all the item nodes and loading them into a dictionary (name/value pairs). So I just need a collection of all the items.
Blankman