[英]c# linq to xml , find nested element by it's attribute
我有一个嵌套元素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
!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.