Search code examples
c#xmlappendchilddocument-root

How to add child element after Root element


I've the following function, that I can pass my C# object to which can then convert it to Xml.

public static XmlDocument SerializeObjectToXML(object obj)
{
  XmlSerializer serializer = 
      new XmlSerializer(obj.GetType());

  using (MemoryStream ms = new MemoryStream())
  {
     XmlDocument xmlDoc = new XmlDocument();
     serializer.Serialize(ms, obj);
     ms.Position = 0;
     xmlDoc.Load(ms);
  }
}

However, I need to add a Child Element after the Root. For example at the moment I have

<MyObjectResponse>
    <Id>1</Id>
    <Name>Mr Smith</Name>
    <Numbers>
      <Number>100</Number>
      <Number>200</Number>
    </Numbers>
</MyObjectResponse>

But want the output to

<MyObjectResponse>
  <Response>
    <Id>1</Id>
    <Name>Mr Smith</Name>
    <Numbers>
      <Number>100</Number>
      <Number>200</Number>
    </Numbers>
  </Response>
</MyObjectResponse>

How can I achieve this ?


Solution

  • Something like this should do the trick:

    XmlDocument xmlDoc = new XmlDocument();
    serializer.Serialize(ms, obj);
    ms.Position = 0;
    xmlDoc.Load(ms);
    
    XmlElement newElem = xmlDoc.CreateElement("Response");
    
    //wrong: works for only 1 child element
    //kept for edit/reference
    //foreach (XmlNode item in xmlDoc.DocumentElement.ChildNodes)
    //{
    //    newElem.AppendChild(item);
    //}
    
    while (xmlDoc.DocumentElement.ChildNodes.Count != 0)
    {
        newElem.AppendChild(xmlDoc.DocumentElement.ChildNodes[0]);
    }
    
    xmlDoc.DocumentElement.AppendChild(newElem);
    

    EDIT replaced the foreach loop with a correct and general implementation using a while loop.