How to make a copy of a XML node with all their child nodes and values but different name C# .NET

Viewed 13467

I'm trying to make a copy of a XML node and all their child nodes but different XML parent node name, but is throwing me an error, this is the xml file:

<Servers>
  <MyServer>
    <Host>0.0.0.0</Host>
     <Port>12</Port>
     <User>USER</User>
  </MyServer>
</Servers>

What I'm trying to do is a copy of MyServer with all their child nodes and values but different name... something like this

<Servers>
  <MyServer>
    <Host>0.0.0.0</Host>
     <Port>12</Port>
     <User>USER</User>
  </MyServer>
  <MyCopyofMyServer>
    <Host>0.0.0.0</Host>
     <Port>12</Port>
     <User>USER</User>
  </MyCopyofMyServer>
</Servers>

What I did was this:

 public void CopyInterface(string NewServer, string ServerToCopy)
 {
    xmldoc.Load(XMLInterfacesFile);
    XmlNode NodeToCopy = xmldoc.SelectSingleNode("Servers/" + ServerToCopy);
    XmlNode deep = NodeToCopy.CloneNode(true);    
    deep.InnerXml = deep.InnerXml.Replace(ServerToCopy, NewServer);
    xmldoc.AppendChild(deep);   //Throwing an exception here!
    xmldoc.Save(XMLInterfacesFile);            
 }

Exception: This document already has a 'DocumentElement' node.

Any Idea?

1 Answers
Related