Serialize an object to XML

后端 未结 17 2183
渐次进展
渐次进展 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:17

    I have a simple way to serialize an object to XML using C#, it works great and it's highly reusable. I know this is an older thread, but I wanted to post this because someone may find this helpful to them.

    Here is how I call the method:

    var objectToSerialize = new MyObject();
    var xmlString = objectToSerialize.ToXmlString();
    

    Here is the class that does the work:

    Note: Since these are extension methods they need to be in a static class.

    using System.IO;
    using System.Xml.Serialization;
    
    public static class XmlTools
    {
        public static string ToXmlString(this T input)
        {
            using (var writer = new StringWriter())
            {
                input.ToXml(writer);
                return writer.ToString();
            }
        }
    
        private static void ToXml(this T objectToSerialize, StringWriter writer)
        {
            new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
        }
    }
    

提交回复
热议问题