Search code examples
c#xmlxelement

Add Xelement in existing XDocument in C#


I have XML with details. I want to copy the entire <Details> node and create updated <Details> node with the exact same attribute.

My XML looks like this:

<root>        
    <Details>
        <A.EMPLID>0000177008</A.EMPLID>
            <G.LAST_NAME>Huziak-Clark</G.LAST_NAME>
            <G.FIRST_NAME>Tracy</G.FIRST_NAME>      
    </Details>      
</root>

I would like to create a new node like this

<root>        
    <Details>
            <A.EMPLID>0000177008</A.EMPLID>
            <G.LAST_NAME>Huziak-Clark</G.LAST_NAME>
            <G.FIRST_NAME>Tracy</G.FIRST_NAME>      
    </Details>  
    <Newdetails>
        <Details>
            <A.EMPLID>0000177008</A.EMPLID>
            <G.LAST_NAME>Huziak-Clark</G.LAST_NAME>
            <G.FIRST_NAME>Tracy</G.FIRST_NAME>      
        </Details>  
    </Newdetails>
</root>

I have used XElement like this, but it is just adding <NewDeatils/> node in XDocument but not remaining nodes.

foreach(XElement e in XDocument.Descendants("Details"))
{
     XDocument.Root.Element.Add("NewDetails",XElement("Deatils");
}

How to select the entire XElement and append it under <Newdetails> node?

Thanks!


Solution

  • First, load the file and get all Descendants named "Details".

    var file = @"XMLFile.xml";
    var doc = XDocument.Load(file);
    var details = doc.Root.Descendants().Where(x => x.Name == "Details");
    

    This gives you a collection of Details nodes, in your example file only one. Then I'd iterate through them, and for each of them create a new XElemen named NewDetails and add the existing element as a child.

    Note here that I'm getting the details.Count() before the loop and using it as the limit. If you did a foreach instead, this will turn into an infinite loop so be careful.

    var count = details.Count();
    for (var i = 0; i < count; i++)
    {
        var newDetails = new XElement("NewDetails");
        newDetails.Add(details);
        doc.Root.Add(newDetails);
    }
    

    Save it to confirm results.

    var fileNew = @"XMLFile2.xml";
    doc.Save(fileNew);
    

    Here's the file before and after adding the node:

    BEFORE:

    enter image description here

    AFTER:

    enter image description here