public class Member
{
public string Num { get; set; }
public string Name { get; set; }
}
public class Team
{
public string Name;
public List<Member> Members { get; set; }
} 假设我们需要把Team类的一个实例POST到一个URL,
/// <summary>
/// 提供xml文档序列化 反序列化
/// </summary>
public sealed class EncodeHelper
{
/// <summary>
/// 反序列化XML字符串为指定类型
/// </summary>
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;
}
/// <summary>
/// 序列化object对象为XML字符串
/// </summary>
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;
}
} 要使用这个类需要添加以下引用
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
下面我们用一个控制台程序来演示一下这个类是如何工作的。这里是程序的Main函数。
static void Main(string[] args)
{
List<Member> Members = new List<Member>();
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();
} 在执行完Console.Write(xml)这行代码后,就可以看到打印出来的XML文档了。
public class Member
{
[XmlElement("Member_Num")]
public string Num { get; set; }
public string Name { get; set; }
}
[XmlRoot("Our_Team")]
public class Team
{
[NonSerialized]public string Name;修正于2012-4-13 [XmlIgnore]public string Name;
public List<Member> Members { get; set; }
}