LINQ to XML subquery<
Posted June 20th, 2008 by Eric WebbI 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<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: linq
Filed under:general
One Response to “LINQ to XML subquery<”
April 1st, 2009 at 7:46 am
[...] recorded first by ShiningSeraph on 2009-02-18→ LINQ to XML subquery [...]
Leave a Reply