Search code examples
c#linqxml-parsingxelement

c# linq to xml , find nested element by it's attribute


I have a nested element xml like below

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

Each If element has uniqKey attribute. Know I want to find uniqKey="3" with linq and add some elements in its tag. it's element.

It's been hours which I'm searching but I didn't find any solution.

Thanks in advance.


Solution

  • To find the element, given:

    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>");
    

    then, quite easily:

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

    (Descendants() returns recursively all the elements)

    Then to add a new element inside the found element:

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

    (clearly you should check that el != null!)