XML解析成对象 对象序列号成xml

前端之家收集整理的这篇文章主要介绍了XML解析成对象 对象序列号成xml前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


就这样直接复制过去就可以用了


  /// <summary>
        /// 对象序列化成 XML String
        /// </summary>
       public static string XmlSerialize<T>(T obj)
       {
           string xmlString = string.Empty;
           try
           {
               XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
               using (MemoryStream ms = new MemoryStream())
               {
                   xmlSerializer.Serialize(ms,obj);
                   xmlString = Encoding.UTF8.GetString(ms.ToArray());
               }
           }
           catch
           {

               return null;
           }
           return xmlString;
       }

        /// <summary>
        /// XML String 反序列化成对象
        /// </summary>
        public static T XmlDeserialize<T>(string xmlString)
        {
            T t = default(T);
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
                {
                    using (XmlReader xmlReader = XmlReader.Create(xmlStream))
                    {
                        Object obj = xmlSerializer.Deserialize(xmlReader);
                        t = (T)obj;
                    }
                }
            }
            catch
            {
                return t;
            }

            return t;
        }

猜你在找的XML相关文章