XML序列化与反序列化
这是一个已经被讲烂了的问题,网上也有很多资料。再写一次主要是想给那些初学者一个清晰的思路和可运行的代码,减少弯路。
先说一下XML。
引述:
可扩展标记语言 (Extensible Markup Language, XML)
,用于标记电子文件使其具有结构性的标记语言,可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。 XML是标准通用标记语言 (SGML) 的子集,非常适合 Web 传输。XML 提供统一的方法来描述和交换独立于应用程序或供应商的结构化数据。
XML序列化与反序列化的目的很简单,把一个对象序列化成XML,然后转交给另外一方,由他来进行反序列化成自己的对象。这样就达到了数据的交换,并且双方的对象无任何关系,所有的表述都已协定好的XML为准。所以不管你是.NET也好,Java也好,都没有关系。很好用吧?
废话留给扯淡用吧,上代码
1、构造对象,我这里构造的是一个学校的对象,里面有英文和中文两个专业,两个专业的老师和教室以及专业中的学生信息等,如下:
[Serializable]
[XmlRoot("school")]
public class TestObject
{
[XmlAttribute("descri")]
public string descri = "Eddy's xml serializaion demo";[XmlElement("English")]
public English english;[XmlElement("Chinese")]
public Chinese chinese;
}public class English
{
[XmlElement("Teacher")]
public string Teacher = "Eddy";[XmlElement("Room")]
public string Room = "202";
}public class Chinese
{
[XmlElement("Teacher")]
public string Teacher = "Eddy";[XmlElement("Room")]
public string Room = "203";[XmlElement("Students")]
public Students students;
}public class Students
{
[XmlElement("Student")]
public List<Student> student;
}public class Student
{
[XmlAttribute("Name")]
public string Name;[XmlAttribute("No")]
public string No;[XmlAttribute("Age")]
public string Age = "19";
}
2、编写序列化和反序列化的方法,如下:
public static string XMLSerialization(object obj)
{
string result = string.Empty;if (obj != null)
{
try
{
XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());using (MemoryStream memoryStream = new MemoryStream())
{
XmlTextWriter writer = new XmlTextWriter(memoryStream, new UTF8Encoding(false));writer.Formatting = Formatting.Indented;
xmlSerializer.Serialize(memoryStream, obj);
writer.Flush();
writer.Close();UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
result = uTF8Encoding.GetString(memoryStream.ToArray());
}
}
catch (Exception ex)
{
throw ex;
}
}return result;
}public static T XMLDeSerialization<T>(string xml)
{
T result = default(T);XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
try
{
using (StringReader stringReader = new StringReader(xml))
{
result = (T)xmlSerializer.Deserialize(stringReader);
}
}
catch (Exception ex)
{
throw ex;
}return result;
}
3、调用示例
TestObject obj = new TestObject()
{
chinese = new Chinese()
{
students = new Students()
{
student = new List<Student>(){
new Student(){
No = "1",
Name = "EddyPeng",
Age = "20"
},
new Student(){
No = "2",
Name = "Eddy's friend",
Age = "20"
}
}
}
},
english = new English()
};string xml = Utility.XMLSerialization(obj);
TestObject obj1 = Utility.XMLDeSerialization<TestObject>(xml);
简单吧,简单也别喷啊,写了半小时呢。。。代码可立即执行。。。