xml與物件的相互轉化
public class XmlHelper
{
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type type, string xml)
{
try
{
using (StringReader sr = new StringReader(xml))
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(sr);
}
}
catch (Exception e)
{
return null;
}
}
public static object Deserialize(Type type, Stream stream)
{
XmlSerializer xmldes = new XmlSerializer(type);
return xmldes.Deserialize(stream);
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">型別</param>
/// <param name="obj">物件</param>
/// <returns></returns>
public static string Serializer(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;
}
}
呼叫方式:
public class CLASS1
{
public object obj
{ get; set;}
}
序列化:
CLASS1 c1 = new CLASS1()
{
obj = "Hello"
};
string strXml = XmlHelper.Serializer(typeof(CLASS1), c1);
反序列化:
c1 = XmlHelper.Deserialize(typeof(CLASS1), strXml) as CLASS1;
注意反序列化的時候要用序列化的xml字首
比如你要反序列化一段xml字串,請先建立其實體類時先序列化一次,取出字首(還有它的關閉標籤!!)然後再把自己要反序列化的字串和字首替換組合一下
string xmlhead = "<?xml version=\"1.0\"?>" +
"<CLASS1 xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">{0}</CLASS1>";
string strXml = string.Format(xmlHead, "你自己的strXml,記得去掉頭部然後再組合");
: -)