Serialize an object to XML

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

    Extension class:

    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace MyProj.Extensions
    {
        public static class XmlExtension
        {
            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();
                    }    
                }
            }
        }
    }
    

    Usage:

    Foo foo = new Foo{MyProperty="I have been serialized"};
    
    string xml = foo.Serialize();
    

    Just reference the namespace holding your extension method in the file you would like to use it in and it'll work (in my example it would be: using MyProj.Extensions;)

    Note that if you want to make the extension method specific to only a particular class(eg., Foo), you can replace the T argument in the extension method, eg.

    public static string Serialize(this Foo value){...}

提交回复
热议问题