这篇文章主要讲述XML与对象的序列化与反序列化。并且会附上一些简单的序列化与反序列化方法,供大家使用。
假设我们在一个Web项目中有这样两个类
复制代码 代码如下:
public class Member
{
public string Num { get; set; }
public string Name { get; set; }
}
public class Team
{
public string Name;
public List
}
复制代码 代码如下:
@model Team
复制代码 代码如下:
复制代码 代码如下:
///
/// 提供xml文档序列化 反序列化
///
public sealed class EncodeHelper
{
///
/// 反序列化XML字符串为指定类型
///
public static object Deserialize(string Xml, Type ThisType)
{
XmlSerializer xmlSerializer = new XmlSerializer(ThisType);
object result;
try
{
using (StringReader stringReader = new StringReader(Xml))
{
result = xmlSerializer.Deserialize(stringReader);
}
}
catch (Exception innerException)
{
bool flag = false;
if (Xml != null)
{
if (Xml.StartsWith(Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble())))
{
flag = true;
}
}
throw new ApplicationException(string.Format("Couldn't parse XML: '{0}'; Contains BOM: {1}; Type: {2}.",
Xml, flag, ThisType.FullName), innerException);
}
return result;
}
///
/// 序列化object对象为XML字符串
///
public static string Serialize(object ObjectToSerialize)
{
string result = null ;
try
{
XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false));
xmlTextWriter.Formatting = Formatting.Indented;
xmlSerializer.Serialize(xmlTextWriter, ObjectToSerialize);
xmlTextWriter.Flush();
xmlTextWriter.Close();
UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
result= uTF8Encoding.GetString(memoryStream.ToArray());
}
}
catch (Exception innerException)
{
throw new ApplicationException("Couldn't Serialize Object:" + ObjectToSerialize.GetType().Name, innerException);
}
return result;
}
}
复制代码 代码如下:
static void Main(string[] args)
{
List
Member member1 = new Member { Name = "Marry", Num = "001" };
Member member2 = new Member { Name = "John", Num = "002" };
Members.Add(member1);
Members.Add(member2);
Team team = new Team { Name = "Development", Members = Members };
var xml =EncodeHelper.Serialize(team);//序列化
Console.Write(xml);//打印序列化后的XML字符串
Console.ReadLine();
Team newTeam = EncodeHelper.Deserialize(xml, typeof(Team)) as Team;//反序列化时需要显式的进行类型转换
Console.WriteLine("Team Name:"+newTeam.Name);//显示反序列化后的newTeam对象
foreach (var member in newTeam.Members)
{
Console.WriteLine("Member Num:" + member.Num);
Console.WriteLine("Member Name:" + member.Name);
}
Console.ReadLine();
}
复制代码 代码如下:
复制代码 代码如下:
public class Member
{
[XmlElement("Member_Num")]
public string Num { get; set; }
public string Name { get; set; }
}
[XmlRoot("Our_Team")]
public class Team
{
[XmlIgnore]public string Name;
public List
}
复制代码 代码如下: