Serialize an object to XML

后端 未结 17 2303
渐次进展
渐次进展 2020-11-22 04:41

I have a C# class that I have inherited. I have successfully \"built\" the object. But I need to serialize the object to XML. Is there an easy way to do it?

It looks

17条回答
  •  半阙折子戏
    2020-11-22 05:30

    It's a little bit more complicated than calling the ToString method of the class, but not much.

    Here's a simple drop-in function you can use to serialize any type of object. It returns a string containing the serialized XML contents:

    public string SerializeObject(object obj)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
            serializer.Serialize(ms, obj);
            ms.Position = 0;
            xmlDoc.Load(ms);
            return xmlDoc.InnerXml;
        }
    }
    

提交回复
热议问题