zoukankan      html  css  js  c++  java
  • 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 ---

  • 相关阅读:
    二十八 .Django中模型类中Meta元对象了解
    【POJ2376】Cleaning Shifts
    【CF600E】Lomsat gelral
    【hiho1035】自驾旅行III
    【模板】manachar
    【hiho1065】全图传送
    【洛谷P1450】硬币购物
    【HDU2204】Eddy's爱好
    【CF208E】Blood Cousins
    【CF451E】Devu and Flowers
  • 原文地址:https://www.cnblogs.com/shadow-abyss/p/14302506.html
Copyright © 2011-2022 走看看