其他分享
首页 > 其他分享> > exercise: 序列化和反序列化Xml --CSharp

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)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (var fs = new FileStream(fileName, FileMode.Truncate, FileAccess.Write))
            {
                xmlSerializer.Serialize(fs, data);
            }
        }

    }

 

    class SomeXmlConfig
    {

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

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


        public SomeXmlConfig()
        {
        }

    }

 

 

 

 

 

--- THE END ---

 

标签:Xml,fs,string,--,fileName,new,xmlSerializer,序列化,public
来源: https://www.cnblogs.com/shadow-abyss/p/14302506.html