views:

61

answers:

1

Getting multiple data items in an element with linq to xml

I have an xml file like this

<TopLevel>
  <Inside>
    Jibba
  </Inside>
  <Inside>
    Jabba
  </Inside>
</TopLevel>

I was given said xml and and want to get all the elements. Here is the code I have.

    var q = from c in loaded.Descendants("TopLevel")
            select (XElement)c.Element("Inside");

I tried c.Elements but that did not work. What do I need to do to get all of the internal elements? This code just gets the first "Inside" tag.

+1  A: 

This should give you "Jibba" and "Jabba"; you'll need using directives for both System.Linq and System.Xml.Linq:

    var q = from c in loaded.Descendants("TopLevel").Elements("Inside")
            select c.Value;

or (less specific, but still works):

    var q = from c in loaded.Descendants("TopLevel").Elements()
            select c.Value;

or if you want to do something more with the elements, SelectMany:

    var q = from c in loaded.Descendants("TopLevel")
            from i in c.Elements("Inside")
            select i.Value;

(if you want the element, not the string, then just select c; or select i; - remove the .Value)

Marc Gravell