tags:

views:

41

answers:

1

I have an xml file which has kind of similar structure that you can see below: I would like to select title and subitems using linq to xml. The difficulties that I have sometimes subitem can be just one and sometimes it can be 20 subitems. and I need to add them to List

<?xml version="1.0"?>
<items>
<item>

 <title>Name of the title</title>
 <subitem>Test</subitem>
 <subitem1>Test</subitem1>
 <subitem2>Test</subitem2>
 <subitem3>Test</subitem3>
 <subitem4>Test</subitem4>
 <subitem5>Test</subitem5>

</item>

<item>

 <title>Name of the title</title>
 <subitem>Test</subitem>
 <subitem1>Test</subitem1>
 <subitem2>Test</subitem2>
 <subitem3>Test</subitem3>
</item>

<item> 
 <title>Name of the title</title>
 <subitem>Test</subitem>
 <subitem1>Test</subitem1>
</item>
</items>
+1  A: 

Edit: Oh, you want titles too, here.

XDocument yourXDocument = XDocument.Load(yourXmlFilePath);
IEnumerable<Tuple<XElement, IEnumerable<XElement>>> yourSubItems =
    yourXDocument.Root.Descendants()
                 .Where(xelem => xelem.Name == "title")
                 .Select(xelem => new Tuple<XElement, IEnumerable<XElement>>(xelem, xelem.Parent.Elements().Where(subelem => subelem.Name.LocalName.StartsWith("subitem")));
Jimmy Hoffa
I suspect you want a ".LocalName" bit in there too.
Jon Skeet
@Jon Skeet: Right, otherwise the extension would require the cast, thanks!
Jimmy Hoffa
OK so how it looks finally if I need to select also title and create foreach loop to add all subitems to the list?
Eugene
@Eugene: Updated for titles as well, sorry didn't read that part of your original post.
Jimmy Hoffa
what is the Tuple mean?
Eugene
@Eugene: A tuple gives you a generic construct to group different types of data together, a Tuple<string,int,DateTime> would be an object which has property Item1 of type string, Item2 of type int, and Item3 of type DateTime, the tuple I created has Item1 which is the title XElement, and Item2 which is an IEnumerable of XElements representing the title's subitems.
Jimmy Hoffa