Serialize an object to XML

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

    Based on above solutions, here comes a extension class which you can use to serialize and deserialize any object. Any other XML attributions are up to you.

    Just use it like this:

            string s = new MyObject().Serialize(); // to serialize into a string
            MyObject b = s.Deserialize();// deserialize from a string
    
    
    
    internal static class Extensions
    {
        public static T Deserialize(this string value)
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
    
            return (T)xmlSerializer.Deserialize(new StringReader(value));
        }
    
        public static string Serialize(this T value)
        {
            if (value == null)
                return string.Empty;
    
            var xmlSerializer = new XmlSerializer(typeof(T));
    
            using (var stringWriter = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
                {
                    xmlSerializer.Serialize(xmlWriter, value);
                    return stringWriter.ToString();
                }
            }
        }
    }
    

提交回复
热议问题