好的,我希望我的链接查询返回用户列表。下面是 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>
而我当前的 LINQ 查询不起作用。doc 是一个 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
});
我得到一个Object reference not set to an instance of an object
例外。谁能告诉我我需要修复什么?
这是我在修复错误的属性名称后的第二次尝试。但是,当我尝试使用它时,或者至少当我尝试将它写入控制台时,这个似乎没有为我枚举 UserName 值。这也返回 8 个总结果我应该只有 2 个结果,因为我只有 2 个用户。
(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()
});