2018年6月27日 星期三

[C#] .NET物件與XML互轉

引用System.Xml.Serialization名稱空間。

.NET物件轉成XML:

public static string ObjToXML(Type objType, object obj)
{
   string oText = string.Empty;
   XmlSerializer mySerializer = new XmlSerializer(objType);
   StringWriter writer = new StringWriter();
   mySerializer.Serialize(writer, obj);
   oText = writer.ToString();
   writer.Close();
   return oText;
}

XML轉成.NET物件:

public static object XMLToObj(Type objType, string oText)
{
   XmlSerializer mySerializer = new XmlSerializer(objType);
   StringReader reader = new StringReader(oText);
   return mySerializer.Deserialize(reader);
}

沒有留言:

張貼留言