0

我有以下函数,我可以将我的 C# 对象传递给该对象,然后可以将其转换为 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);
  }
}

但是,我需要在 Root 之后添加一个子元素。例如目前我有

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

但希望输出到

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

我怎样才能做到这一点?

4

1 回答 1

0

这样的事情应该可以解决问题:

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使用循环将循环替换foreach为正确且通用的实现while

于 2013-11-11T11:22:55.043 回答