我有以下XML结构:
<Capabilities>
<Capability ID="1" Name="Capability # 1">
<Relations>
<Relation RelatedTo="2" RelationType="Child"/>
<Relation RelatedTo="3" RelationType="Child"/>
<Relation RelatedTo="4" RelationType="Child"/>
<Relation RelatedTo="5" RelationType="Child"/>
</Relations>
</Capability>
<Capability ID="3" Name="Capability # 3">
<Relations>
<Relation RelatedTo="1" RelationType="Dependant" />
</Relations>
</Capability>
<Capability ID="2" Name="Capability # 2">
<Relations>
<Relation RelatedTo="6" RelationType="Child" />
<Relation RelatedTo="5" RelationType="Child" />
</Relations>
</Capability>
</Capabilities>
我需要使用具有值5的RelatedTo属性的Child关系查询所有Capabilities。 到目前为止,我已尝试使用以下查询,但我收到了“空引用异常”的集合,我无法弄清楚如何执行此操作。
var result = root.Elements("Capability")
.Where(c => c.Elements("Relations")
.Where(r => r.Attribute("RelatedTo").Value == "5"
&& r.Attribute("").Value == Enum.GetName(typeof(RelationTypes), RelationTypes.Children)).Any());
关于我做错了什么或者查询它的正确方法的任何线索?
答案 0 :(得分:4)
var capabilites = root.Descendants("Capability")
.Where(c => c.Descendants("Relation")
.Any(r => (string)r.Attribute("RelatedTo") == "5"))
.ToList();
答案 1 :(得分:1)
此:
var xDoc = XDocument.Parse(
@"<Capabilities>
<Capability ID=""1"" Name=""Capability # 1"">
<Relations>
<Relation RelatedTo=""2"" RelationType=""Child""/>
<Relation RelatedTo=""3"" RelationType=""Child""/>
<Relation RelatedTo=""4"" RelationType=""Child""/>
<Relation RelatedTo=""5"" RelationType=""Related""/>
</Relations>
</Capability>
<Capability ID=""3"" Name=""Capability # 3"">
<Relations>
<Relation RelatedTo=""1"" RelationType=""Dependant"" />
</Relations>
</Capability>
<Capability ID=""2"" Name=""Capability # 2"">
<Relations>
<Relation RelatedTo=""6"" RelationType=""Child"" />
<Relation RelatedTo=""5"" RelationType=""Child"" />
</Relations>
</Capability>
</Capabilities>");
var q = xDoc.Descendants("Capability").
Where(c => c.Descendants("Relation").Where(r => (int)r.Attribute("RelatedTo") == 5).Any());
foreach (var r in q)
{
Console.WriteLine(r);
}
结果:
<Capability ID="1" Name="Capability # 1">
<Relations>
<Relation RelatedTo="2" RelationType="Child" />
<Relation RelatedTo="3" RelationType="Child" />
<Relation RelatedTo="4" RelationType="Child" />
<Relation RelatedTo="5" RelationType="Related" />
</Relations>
</Capability>
<Capability ID="2" Name="Capability # 2">
<Relations>
<Relation RelatedTo="6" RelationType="Child" />
<Relation RelatedTo="5" RelationType="Child" />
</Relations>
</Capability>
Press any key to continue . . .
我认为你的目标是什么......