Serialize an object to XML

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

    You can use the function like below to get serialized XML from any object.

    public static bool Serialize(T value, ref string serializeXml)
    {
        if (value == null)
        {
            return false;
        }
        try
        {
            XmlSerializer xmlserializer = new XmlSerializer(typeof(T));
            StringWriter stringWriter = new StringWriter();
            XmlWriter writer = XmlWriter.Create(stringWriter);
    
            xmlserializer.Serialize(writer, value);
    
            serializeXml = stringWriter.ToString();
    
            writer.Close();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
    

    You can call this from the client.

提交回复
热议问题