Search code examples
c#xmllinqxelement

c#, update child node in XML


I have an xml file 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.


Solution

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