zoukankan      html  css  js  c++  java
  • XmlSerialization示例

    1.准备要序列化的对象

    [Serializable()]
    public class SerializableType
    {
        public string StringValue { get; set; }
        public bool BoolValue { get; set; }
        public int IntValue { get; set; }
        public AnotherType AnotherTypeValue { get; set; }
        public List<string> ListValue { get; set; }
    
        [NonSerialized()]
        private int ignoredField = 1;
    
        public SerializableType()
        {
            ListValue = new List<string>();
            AnotherTypeValue = new AnotherType();
        }
    };
    
    [Serializable()]
    public class AnotherType
    {
        public string StringValue { get; set; }
        public int IntValue { get; set; }
    };
    
    

    2.序列化

        static void Serialize(SerializableType instance)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(SerializableType));
    
            using (StreamWriter streamWriter = File.CreateText("CSXmlSerialization.xml")) {
                serializer.Serialize(streamWriter, instance);
            }
        }
    
    

    3. 解序列化

        static SerializableType Deserialize()
        {
            var deserializedInstance = new SerializableType();
            var serializer = new XmlSerializer(typeof(SerializableType));
    
            using (StreamReader streamReader = File.OpenText("CSXmlSerialization.xml")) {
                deserializedInstance = serializer.Deserialize(streamReader) as SerializableType;
            }
            return deserializedInstance;
        }
    
    

    4. 测试代码

        static void Main(string[] args)
        {
            SerializableType st = new SerializableType();
            st.BoolValue = true;
            st.IntValue = 1;
            st.StringValue = "Test String";
            st.ListValue.Add("List Item 1");
            st.ListValue.Add("List Item 2");
            st.ListValue.Add("List Item 3");
            st.AnotherTypeValue.IntValue = 2;
            st.AnotherTypeValue.StringValue = "Inner Test String";
    
            Serialize(st);
    
            var dt = Deserialize();
    
            Console.WriteLine("BoolValue: {0}", dt.BoolValue);
            Console.WriteLine("IntValue: {0}", dt.IntValue);
            Console.WriteLine("StringValue: {0}", dt.StringValue);
            Console.WriteLine("AnotherTypeValue.IntValue: {0}", dt.AnotherTypeValue.IntValue);
            Console.WriteLine("AnotherTypeValue.StringValue: {0}", dt.AnotherTypeValue.StringValue);
            Console.WriteLine("ListValue: ");
    
            foreach (object obj in dt.ListValue) {
                Console.WriteLine(obj.ToString());
            }
        }
    
    
  • 相关阅读:
    函数-列表生成式
    函数-闭包
    函数-参数
    函数-装饰器
    函数-函数递归
    函数-高阶函数
    函数-命名空间
    函数-匿名函数
    模块-shutil
    在 Android 5.1.1 执行 remount system failed 解决方法
  • 原文地址:https://www.cnblogs.com/cuishengli/p/1901573.html
Copyright © 2011-2022 走看看