[Memo]將XML轉為對應的Entity

  • 5566
  • 0

[Memo]將XML轉為對應的Entity

前言
日常作業上很常用的到這個需求,所以記錄一下。

Sample
1. 將XML字串Deserialize成對應的Entity


        /// <summary>
        /// XMLs to entity.
        /// </summary>
        /// <typeparam name="T">Xml對應的Entity type</typeparam>
        /// <param name="xml">The XML.</param>
        /// <returns>Xml對應的Entity</returns>
        public static T XmlToEntity<T>(string xml) where T : class
        {
            if (string.IsNullOrEmpty(xml))
            {
                return null;
            }
            else
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                byte[] byteArray = Encoding.UTF8.GetBytes(xml);
                MemoryStream stream = new MemoryStream(byteArray);

                return serializer.Deserialize(stream) as T;
            }
        }

2. 將Entity物件Serialize成某個xml檔案


            XmlSerializer serializer = new XmlSerializer(typeof(MyXmlEntity));
            var o = new MyXmlEntity { 屬性初始化 };
            serializer.Serialize(File.OpenWrite(@".\MyXml.xml"), o);

 


blog 與課程更新內容,請前往新站位置:http://tdd.best/