Maestro1024
Maestro1024

Reputation: 3293

Getting multiple data items in an element with linq to xml

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.

Upvotes: 1

Views: 607

Answers (2)

Matt
Matt

Reputation: 1431

I needed to take this a step further and wasn't real clear as to how to do it. Thanks for the jump off point. Here's some additional fruit to save some labor.

Given some additional xml fun:

<TopLevel>
    <Inside ident="one">Jibba</Inside>
    <Inside ident="two">Jabba</Inside>
    <Inside ident="one">AlsoJibba</Inside>
    <Inside ident="three">AlsoJabba</Inside>
</TopLevel>

I added a where clause that looks for elements inside the parent "TopLevel" that have an ident attribute value of "one".

Dim query = From c In loaded.Descendants("TopLevel").Elements("inside")
            Where c.Attribute("ident") = "one"
            Select c.Value

Then did a little demo console run of the results:

For each inside in query
    Console.WriteLine(inside)
Next

Which output:

Jibba
AlsoJibba

Spoiler Alert Ahead:

Now if you copy pasted what I just did and you are using VB like I am you have an especially annoying nuance. The code doesn't work. Notice the little section ".Elements("inside") in the LINQ query. XML is case sensitive. VB is extremely not case sensitive. C# users please feel free to ignore our youth. Just wanted to demonstrate a where, and a gotcha.

Matt

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064024

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)

Upvotes: 1

Related Questions