实体 和 XML格式的转换

许多接口传输需要XML格式转换,那么如何实现?看下面帮助类→_→

  /// <summary>
    /// XML处理帮助类,编码格式GBK!!
    /// </summary>
    public class XmlUtility
    {
        /// <summary>
        /// 将自定义对象序列化为XML字符串
        /// </summary>
        /// <param name="myObject">自定义对象实体</param>
        /// <returns>序列化后的XML字符串</returns>
        public static string SerializeToXml<T>(T obj)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                StreamWriter sw = new StreamWriter(ms, Encoding.GetEncoding("GBK"));
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                Type t = obj.GetType();
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(sw, obj, ns);

                string xmlMessage = Encoding.GetEncoding("GBK").GetString(ms.GetBuffer());
                sw.Close();
                ms.Close();
                return xmlMessage.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("将实体对象转换成XML异常", ex);
            }
        }

        /// <summary>
        /// 将XML字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="xml">XML字符</param>
        /// <returns></returns>
        public static T DeserializeToObject<T>(string xml) where T : class
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("将XML转换成实体对象异常", ex);
            }
        }
    }

根据上面类我简单写了一个Demo:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //获取参数
            RequestModel r = new RequestModel();
            UpdateModel<RequestModel>(r);
            //拼接参数展示文字
            string msg = r.Name + "今年" + r.Age + "岁了";
            return Content(msg);
        }
    
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }

 

posted @ 2019-06-02 18:13  shuai7boy  阅读(1332)  评论(0编辑  收藏  举报