LINQ To XML - How to query for all the elements in an inner element?
<Results>
<ResultSet>"nothing special" Description="More of nothing"
<Results>
<Result>
<Body>Four in this group</Body>
<Body2>this is more stuff I want</Body2>
<Body3>This is interesting stuff I want</Body3>
<Body4>this is more stuff I want</Body4>
</Result>
<Result>
<Something1>Only 3 in the group</Something1>
<ID>this is more stuff I want</ID>
<Stuff>This is interesting stuff I want</Stuff>
</Result>
<Result>
<Tag1>Only 3 in the group</Tag1>
<Tag2>this is more stuff I want</Tag2>
<Tag3>This is interesting stuff I want</Tag3>
</Result>
</Results>
</ResultSet>
</Results>
How would I use Linq to XML to pull out all the <Result>
blocks? As you can see each block can have any number of elements and I won't know what they are called. My end goal is to package these blocks up into objects that I will then pass around my app.
The issue I have is I can't get each group broken out seperatly using Linq. The closest I can get is returning all elements within ALL the <Result>
groups into one big lis开发者_如何学编程t (using Descendants).
Edit: This is the code I am using to bring back everything in each <Result>
group. I can't figure out how to iterate through list from this query to break out the name/value pairs. I don't know the names of the elements, so I can't reference them by name. At the end, I just want the name/value pair of each element within each <Result>
.
var query = from item in xml.Descendants("Result")
select item;
Any help?
Thanks, -Scott
Descendants will grab all descendant nodes with the given name. If you want to be specific you need to walk down the XML hierarchy element by element, such as xml.Element("ResultSet").Element("Results").Elements("Result")
.
This should point you in the right direction:
var query = xml.Descendants("Result")
.Select(r => r.Elements()
.Select(e => new { Name = e.Name.LocalName, Value = e.Value }));
foreach (var result in query)
{
foreach (var item in result)
{
Console.WriteLine("{0} : {1}", item.Name, item.Value);
}
}
Alternately, you can use SelectMany
and flatten the result set:
var query = xml.Descendants("Result")
.SelectMany(r => r.Elements()
.Select(e => new { Name = e.Name.LocalName, Value = e.Value }));
foreach (var item in query)
{
Console.WriteLine("{0} : {1}", item.Name, item.Value);
}
精彩评论