c#, update child node in XML

I have an 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>

Now I want to find uniqKey=3 and insert

<Task id="3" xmlns="urn:workflow-schema">
  <Parent id="-1" />
</Task>

Into its <Do> tag.

Whatever I tried is the below c# code.

var element = xGraph
    .Descendants()
    .Where(x => (string)x.Attribute("uniqKey") == parent.Key.ToString()).first();

Now elemenet has whole tag but I cant insert my task into it's <DO> child.

Desired Output:

<ExecutionGraph>
<If uniqKey="1">
    <Do>
        <If uniqKey="6">
            <Do />
            <Else />
        </If>
    </Do>
    <Else>
        <If uniqKey="2">
            <Do />
            <Else>
                <If uniqKey="3">
                    <Do>
                        <Task id="3"
                            xmlns="urn:workflow-schema">
                            <Parent id="-1" />
                        </Task>
                    </Do>
                    <Else />
                </If>
            </Else>
        </If>
    </Else>
</If>

Thanks in advance.

1 answer

  • answered 2018-05-16 05:05 Sangram Nandkhile

    string str = "<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>";
                XDocument doc = XDocument.Parse(str);
                var element = doc
                                .Descendants()
                                .Where(x => (string)x.Attribute("uniqKey") == "3").FirstOrDefault().Element("Do");
                XElement task = XElement.Parse("<Task id='3' xmlns='urn:workflow-schema'><Parent id='-1' /></Task>");
                element.Add(task);
    

    output:

    <If uniqKey="3">
                <Do>
                  <Task id="3" xmlns="urn:workflow-schema">
                    <Parent id="-1" />
                  </Task>
                </Do>
                <Else />
              </If>