LINQ to XML subquery<

I didn’t find a clear example online about how to do a subquery of an element, so I thought I would share.

First, here’s the XML I’m reading:

&lt;response&gt; 
    &lt;name&gt;Test&lt;/name&gt; 
    &lt;states&gt; 
        &lt;state&gt;OH&lt;/state&gt; 
        &lt;state&gt;MI&lt;/state&gt; 
    &lt;/states&gt; 
&lt;/response&gt;

I want to use LINQ to parse through the responses and create new objects for each one of them.  The object I created to hold the info is below:

[Serializable()]
    public class User
    {
        public string userName { get; set; }a
        public List<string> states { get; set; }

        public User(string UserName,List<string> States)
        {
            userName = UserName;
            states = States;
        }
    }

I was at a loss at how to get the state elements into my “States” list. Here’s the query I ended up using:

var responses = from response in loginResult.Descendants("response")
      select new
      {
            authenticationToken = response.Element("authentication_token").Value,
            states = (from st in response.Descendants("states").Elements()
                         select st.Value).ToList(),

      };

It was obvious after I got it and I probably should have been able to figure it out quicker, but such as life when learning something new.

Tags:

Filed under:general

One Response to “LINQ to XML subquery<”

Leave a Reply