繁体   English   中英

将自定义类序列化为XML

[英]Serializing a custom class to XML

我有一个包含SortedList<string, Data>作为私有字段的类,其中Data是带有一些intDateTimeNullable<DateTime>字段的简单自定义类。

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

    ...
}

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

我应该如何进行?

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

好的,您只需要用[Serializable]属性装饰类即可,它应该可以工作。 但是,您有一个实现IDictionary的SortedList,并且这些序列不能使用IXMLSerializable进行序列化,因此需要在此处进行一些自定义

序列化.NET字典

但是,如果将排序列表更改为普通列表或任何未实现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;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM