Serialize an object to XML

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

    public string ObjectToXML(object input)
    {
        try
        {
            var stringwriter = new System.IO.StringWriter();
            var serializer = new XmlSerializer(input.GetType());
            serializer.Serialize(stringwriter, input);
            return stringwriter.ToString();
        }
        catch (Exception ex)
        {
            if (ex.InnerException != null)
                ex = ex.InnerException;
    
            return "Could not convert: " + ex.Message;
        }
    }
    
    //Usage
    var res = ObjectToXML(obj)
    

    You need to use following classes:

    using System.IO;
    using System.Xml;
    using System.Xml.Serialization;
    

提交回复
热议问题