Serialize an object to XML

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

    The following function can be copied to any object to add an XML save function using the System.Xml namespace.

    /// 
    /// Saves to an xml file
    /// 
    /// File path of the new xml file
    public void Save(string FileName)
    {
        using (var writer = new System.IO.StreamWriter(FileName))
        {
            var serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(writer, this);
            writer.Flush();
        }
    }
    

    To create the object from the saved file, add the following function and replace [ObjectType] with the object type to be created.

    /// 
    /// Load an object from an xml file
    /// 
    /// Xml file name
    /// The object created from the xml file
    public static [ObjectType] Load(string FileName)
    {
        using (var stream = System.IO.File.OpenRead(FileName))
        {
            var serializer = new XmlSerializer(typeof([ObjectType]));
            return serializer.Deserialize(stream) as [ObjectType];
        }
    }
    

提交回复
热议问题