C# Asp.net中xml串與對象互相轉換
阿新 • • 發佈:2017-10-12
try res return class 類型 mls log throw XML
public class ShuangchengPayQueryResponse
{
public string name { get; set; }
public string age { get; set; }
} xml串: <xml> <people> <name>LiMing</name> <age>25</age> </people> </xml>
public class XmlUtil { #region 反序列化 /// <summary> /// 將XML字符串反序列化為對象 /// </summary> /// <param name="type">類型</param> /// <param name="xml">XML字符串</param> /// <returns></returns> public static object Xml2Obj(Type type, stringxml) { 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> publicstatic 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串與對象互相轉換