今天遇到需要將DTO與XML相互轉換,但卻一直遇到狀況。
後續處理完畢,特別紀錄一下。
XML:
<massege> <header code="OTP" id="PUSID"> <from>127.0.0.1</from> <to>255.0.0.0</to> </header> <body> 訊息內容 </body> </message>
DTO:
[XmlTypeAttribute(AnonymousType = true)] [XmlRootAttribute(Namespace = "", IsNullable = false, ElementName = "message")] public class TestMessage { public TestMessageHeader header{get;set;} public string body{get;set;} } [XmlTypeAttribute(AnonymousType = true)] public class TestMessageHeader { [XmlAttributeAttribute()] public string code { get; set; } = string.Empty; [XmlAttributeAttribute()] public string id { get; set; } = string.Empty; public string from {get;set;} = string.Empty; public string to{get;set;} = string.Empty; }
程式碼:
public static string XmlToDto<T>(string xml, ref T obj) where T : class { XmlSerializer Serializer = new XmlSerializer(typeof(T)); try { using (StringReader reader = new StringReader(xml)) { obj = (T)Serializer.Deserialize(reader); } return "0000"; } catch (Exception ex) { return ex.Message; } } public static string XmlToDto<T>(string xml, string rootTag, ref T obj) where T : class { XmlSerializer Serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(rootTag)); try { using (StringReader reader = new StringReader(xml)) { obj = (T)Serializer.Deserialize(reader); } return "0000"; } catch (Exception ex) { return ex.Message; } }
參考網頁:https://dotblogs.com.tw/initials/2020/11/18/184450