C# LINQ to XML ,按其属性查找嵌套元素



我有一个嵌套元素xml,如下所示

<ExecutionGraph>
<If uniqKey="1">
<Do>
<If uniqKey="6">
<Do />
<Else />
</If>
</Do>
<Else>
<If uniqKey="2">
<Do />
<Else>
<If uniqKey="3">
<Do />
<Else />
</If>
</Else>
</If>
</Else>
</If>
</ExecutionGraph>

每个 If 元素都有uniqKey属性。知道我想用linq找到uniqKey="3"并在其标签中添加一些元素。它是元素。

我已经搜索了几个小时,但我没有找到任何解决方案。

提前谢谢。

要查找元素,给定:

XDocument doc = XDocument.Parse(@"<ExecutionGraph>
<If uniqKey=""1"">
<Do>
<If uniqKey=""6"">
<Do />
<Else />
</If>
</Do>
<Else>
<If uniqKey=""2"">
<Do />
<Else>
<If uniqKey=""3"">
<Do />
<Else />
</If>
</Else>
</If>
</Else>
</If>
</ExecutionGraph>");

然后,很容易:

var el = doc.Descendants()
.Where(x => (string)x.Attribute("uniqKey") == "3")
.FirstOrDefault();

(Descendants()递归返回所有元素(

然后在找到的元素内添加一个新元素:

var newElement = new XElement("Comment");
el.Add(newElement);

(显然你应该检查一下el != null

最新更新