Serialize an object to XML

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

    I modified mine to return a string rather than use a ref variable like below.

    public static string Serialize(this T value)
    {
        if (value == null)
        {
            return string.Empty;
        }
        try
        {
            var xmlserializer = new XmlSerializer(typeof(T));
            var stringWriter = new StringWriter();
            using (var writer = XmlWriter.Create(stringWriter))
            {
                xmlserializer.Serialize(writer, value);
                return stringWriter.ToString();
            }
        }
        catch (Exception ex)
        {
            throw new Exception("An error occurred", ex);
        }
    }
    

    Its usage would be like this:

    var xmlString = obj.Serialize();
    

提交回复
热议问题