码迷,mamicode.com
首页 > Windows程序 > 详细

C# Asp.net中xml串与对象互相转换

时间:2017-10-12 23:09:01      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:stat   exce   mlu   osi   col   region   class   val   obj   

public class XmlUtil
    {
        #region 反序列化
        /// <summary>
        /// 将XML字符串反序列化为对象
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="xml">XML字符串</param>
        /// <returns></returns>
        public static object Xml2Obj(Type type, string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(type);
                    return xmldes.Deserialize(sr);
                }
            }
            catch (Exception e)
            {

                return null;
            }
        }
        #endregion

        #region 对象转化成
        /// <summary>
        /// 对象转化成XML
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string Obj2Xml(Type type, object obj)
        {
            MemoryStream Stream = new MemoryStream();
            XmlSerializer xml = new XmlSerializer(type);
            try
            {
                //序列化对象
                xml.Serialize(Stream, obj);
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            Stream.Position = 0;
            StreamReader sr = new StreamReader(Stream);
            string str = sr.ReadToEnd();

            sr.Dispose();
            Stream.Dispose();

            return str;
        }

        #endregion
    }

对象类:

 [XmlRoot("people")]
    public class ShuangchengPayQueryResponse
    {
        public string name { get; set; }
        public string age { get; set; }
    } 
 
xml串:
<xml>
<people>
<name>LiMing</name>
<age>25</age>
</people>
</xml>

C# Asp.net中xml串与对象互相转换

标签:stat   exce   mlu   osi   col   region   class   val   obj   

原文地址:http://www.cnblogs.com/qk2014/p/7658347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!