c#linq to xml,通过它的属性查找嵌套元素

时间:2018-05-15 11:28:50

标签: c# linq xml-parsing xelement

我有一个嵌套元素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"并在其标记中添加一些元素。它的元素。

我一直在寻找几个小时,但我找不到任何解决方案。

提前致谢。

1 个答案:

答案 0 :(得分:2)

要找到元素,请给出:

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!)

相关问题