實體 和 XML格式的轉換

許多接口傳輸須要XML格式轉換,那麼如何實現?看下面幫助類→_→app

  /// <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();
        }
    }

相關文章
相關標籤/搜索