views:

64

answers:

2

I have a XML file, like this:

<?xml version="1.0" encoding="utf-8" ?>
<ROOT>
    <NAME>
        ItemName
    </NAME>
    <LIST>
       <ITEM>
          ListItem1
       </ITEM> 
       <ITEM>
          ListItem2
       </ITEM> 
       <ITEM>
          ListItem3
       </ITEM> 
    </LIST>
</ROOT>

How can I use LINQ to get all the ITEMs inside the LIST tag?

+2  A: 

Something like:

XDocument doc = XDocument.Load("foo.xml");
var items = from list in doc.Descendants("LIST")
            from item in list.Elements("ITEM")
            select item;

That will cope with multiple "LIST" elements, and won't find "ITEM" elements except directly under "LIST" ones. If you don't care about those finer points you could just use:

XDocument doc = XDocument.Load("foo.xml");
var items = doc.Descendants("ITEM");
Jon Skeet
+1  A: 

An alternative syntax would be to chain the Descendents method to specifically get the ITEM nodes which are children of the LIST nodes:

XDocument doc = XDocument.Load("foo.xml");
var nodes = doc.Descendants("LIST").Descendants("ITEM");
Andy Rose
I wouldn't really call that an 'alternative' - it is semantically identical to Jon's first answer, just using a method chain instead of query syntax.
Rob H
Edited the answer to reflect that it is alternative syntax.
Andy Rose