exercise: 序列化和反序列化Xml --CSharp

 

 

 

    class XmlHelper
    {


        public XmlHelper()
        {
        }



        /// <summary>
        /// 读取 xml 文件内容
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T Load<T>(string fileName)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                return (T)xmlSerializer.Deserialize(fs);
            }
        }

        /// <summary>
        /// 写入 xml 文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <param name="data"></param>
        public static void Write<T>(string fileName, T data)
        {
            XmlWriterSettings settings = new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "    ",
                NewLineChars = Environment.NewLine,
                Encoding = Encoding.UTF8
            };

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);

            using (var fs = new FileStream(fileName, FileMode.Truncate, FileAccess.Write))
            {
                using (XmlWriter writer = XmlWriter.Create(fs, settings))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(writer, data, ns);
                }
            }
        }

    }

 

 

 

 

 

    class SomeXmlConfig
    {

        [XmlElement("hello")]
        public string Hello { get; set; }

        [XmlElement("world")]
        public string World { get; set; }


        public SomeXmlConfig()
        {
        }

    }

 

 

 

 

 

--- THE END ---

 

posted @ 2021-01-20 13:54  太初谷神  阅读(104)  评论(0编辑  收藏  举报