Search code examples
xmlxml-parsingdynamic-reports

Need to insert XML tags based on conditions


I am trying to insert few nodes to my XML file, based on few conditions.

This is my XML

<root>
<child name="abc">
<child name="xyz">

</root>

So now my condition is somthing like this ..

if(root/child[name="xyz"]) insert child2  under that tag

So my final XML should look like this

<root>
<child name="abc">
<child name="xyz">
<child2></child2>

</root>

Need programmatic help to achieve this.


Solution

  • string xml = @"<root>
        <child name='abc'></child>
        <child name='xyz'></child>
    </root>";
    
    XDocument doc = XDocument.Parse(xml);  //replace with xml file path
    doc.Root
        .Elements("child")
        .Single(c => (string) c.Attribute("name") == "xyz")
        .AddAfterSelf(new XElement("child2", ""));
    
    Console.WriteLine(doc.ToString());
    

    returns

    <root>
       <child name="abc"></child>
       <child name="xyz"></child>
       <child2></child2>
    </root>