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
});
I get an Object reference not set to an instance of an object exception. 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()
});
Your
defaultelements don’t have ausernameattribute,usernameis a value of thepropertyattribute.And here’s how your query should probably look as an alternative to what
Henk Holtermanwrote. The difference being I selecting at theUserelement level rather than at thedefault[@property='UserName']element level.Compared to your second attempt the code
from prop in user.Descendants("default")has been moved into the anonymous type constructor and the assignment to UserName has been simplified.