Arash
Arash

Reputation: 1826

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.

Upvotes: 0

Views: 193

Answers (1)

Sangram Nandkhile
Sangram Nandkhile

Reputation: 18202

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>

Upvotes: 1

Related Questions