1

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.

2
  • What have you tried so far? Commented May 15, 2018 at 11:32
  • Actually I have no idea where to start to solve this solution Commented May 15, 2018 at 11:34

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I thought Descendant() function will list only children of the root. Thanks :)
@Arash doc.Descendants().ToArray() and you can see that it returns everything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.