Skip to main content
 首页 » 编程设计

c#之将自定义类序列化为 XML

2024年02月23日15exmyth

我有一个包含 SortedList<string, Data> 的类作为私有(private)领域,其中 Data是一个简单的自定义类,其中包含一些 int , DateTime和 Nullable<DateTime>字段。

public class CustomCollection 
{ 
    private SortedList<string, Data> _list; 
 
    ... 
} 

现在我要使我的类可序列化,这样我就可以将其内容(即 _list 字段的项目)写入 XML 文件或从现有 XML 文件加载数据。

我应该如何进行?

我想我知道有两种序列化方法:第一种是将所有字段标记为可序列化,而第二种是实现 IXmlSerializable界面。如果我没理解错,这两种方式什么时候可以使用?

请您参考如下方法:

好的,你只需要用 [Serializable] 属性装饰你的类,它应该可以工作。但是,您有一个实现 IDictionary 的 SortedList,这些不能用 IXMLSerializable 序列化,因此需要做一些定制,看这里

Serializing .NET dictionary

但是如果您将排序列表更改为普通列表或任何未实现 IDictionary 的列表,那么下面的代码将起作用 :-) 将其复制到控制台应用程序并运行它。

namespace ConsoleApplication1 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Data d = new Data { CurrentDateTime = DateTime.Now, DataId = 1 }; 
            Data d1 = new Data { CurrentDateTime = DateTime.Now, DataId = 2 }; 
            Data d2 = new Data { CurrentDateTime = DateTime.Now, DataId = 3 }; 
 
            CustomCollection cc = new CustomCollection 
                                      {List = new List<Data> {d, d1, d2}}; 
 
            //This is the xml 
            string xml = MessageSerializer<CustomCollection>.Serialize(cc); 
 
            //This is deserialising it back to the original collection 
            CustomCollection collection = MessageSerializer<CustomCollection>.Deserialize(xml); 
        } 
    } 
 
    [Serializable] 
    public class Data 
    { 
        public int DataId; 
        public DateTime CurrentDateTime; 
        public DateTime? CurrentNullableDateTime; 
    } 
 
    [Serializable] 
    public class CustomCollection 
    { 
        public List<Data> List; 
    } 
 
    public class MessageSerializer<T> 
    { 
        public static T Deserialize(string type) 
        { 
            var serializer = new XmlSerializer(typeof(T)); 
 
            var result = (T)serializer.Deserialize(new StringReader(type)); 
 
            return result; 
        } 
 
        public static string Serialize(T type) 
        { 
            var serializer = new XmlSerializer(typeof(T)); 
            string originalMessage; 
 
            using (var ms = new MemoryStream()) 
            { 
                serializer.Serialize(ms, type); 
                ms.Position = 0; 
                var document = new XmlDocument(); 
                document.Load(ms); 
 
                originalMessage = document.OuterXml; 
            } 
 
            return originalMessage; 
        } 
    } 
}