Tag Archives: Linq

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:


<response> 
    <name>Test</name> 
    <states> 
        <state>OH</state> 
        <state>MI</state> 
    </states> 
</response> 

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 states { get; set; }

        public User(string UserName,List 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.

Switch to our mobile site