Retrieve nested list from XDocument with LINQ
Posted
by
twreid
on Stack Overflow
See other posts from Stack Overflow
or by twreid
Published on 2012-06-15T19:30:01Z
Indexed on
2012/06/15
21:16 UTC
Read the original article
Hit count: 166
Ok I want my link query to return a list of users. Below is the XML
<section type="Users">
<User type="WorkerProcessUser">
<default property="UserName" value="Main"/>
<default property="Password" value=""/>
<default property="Description" value=""/>
<default property="Group" value=""/>
</User>
<User type="AnonymousUser">
<default property="UserName" value="Second"/>
<default property="Password" value=""/>
<default property="Description" value=""/>
<default property="Group" value=""/>
</User>
</section>
And my current LINQ Query that doesn't work. doc is an XDocument
var users = (from iis in doc.Descendants("section")
where iis.Attribute("type").Value == "Users"
from user in iis.Elements("User")
from prop in user.Descendants("default")
select new
{
Type = user.Attribute("type").Value,
UserName = prop.Attribute("UserName").Value
});
This does not work can anyone tell me what I need to fix?
Here is my second attempt after fixing for the wrong property name. However this one does not seem to enumerate the UserName value for me when I try to use it or at least when I try to write it to the console. Also this returns 8 total results I should only have 2 results as I only have 2 users.
(from iis in doc.Descendants("section")
where iis.Attribute("type").Value == "Users"
from user in iis.Elements("User")
from prop in user.Descendants("default")
select new
{
Type = user.Attribute("type").Value,
UserName = (from name in prop.Attributes("property")
where name.Value == "UserName"
select name.NextAttribute.Value).ToString()
});
© Stack Overflow or respective owner