最近新项目一些数据文件都是XML文件,这样就涉及到对XML文件的测试。所以就抽时间把相关的知识整理归纳下。
什么是XML序列化与反序列化?
XML序列化将对象的公共字段和属性值序列化为XML流,以便传输或存储。反序列化根据流重新构造对象。XmlSerializer 类使你得以控制如何将对象编码到 XML 中。
以下是段简单的XML序列化与反序列化代码:
1 using System; 2 using System.Text; 3 using System.Collections.Generic; 4 using System.Xml; 5 using System.Xml.Serialization; 6 7 namespace TestXML 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //将序列化的结果输出到XML文件里 14 List<Book> books = new List<Book>(); 15 books.Add(new Book() { Author = "Lynn", Price = 100, Title = "C#" }); 16 books.Add(new Book() { Author = "Jason", Price = 100, Title = "J#" }); 17 Helper.Serialize<List<Book>>(books, "ExportBooks.xml"); 18 19 ////输出反序列化结果到控制台 20 //Books books = Helper.Deserialize<Books>("Books.xml"); 21 //foreach (Book book in books.ArrayOfBooks) 22 //{ 23 // Console.WriteLine(book.Title + "'s price: " + book.Price); 24 //} 25 } 26 } 27 28 public class Helper 29 { 30 public static T Deserialize<T>(string fileName) 31 { 32 using (XmlTextReader reader = new XmlTextReader(fileName)) 33 { 34 XmlSerializer serializer = new XmlSerializer(typeof(T)); 35 36 return (T)serializer.Deserialize(reader); 37 } 38 } 39 40 public static void Serialize<T>(T obj, string fileName) 41 { 42 using (XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8)) 43 { 44 XmlSerializer serializer = new XmlSerializer(typeof(T)); 45 46 serializer.Serialize(writer, obj); 47 } 48 } 49 } 50 51 public class Books 52 { 53 [XmlElement("Book")] 54 public Book[] ArrayOfBooks { get; set; } 55 } 56 57 public class Book 58 { 59 public decimal Price { get; set; } 60 public string Title { get; set; } 61 public string Author { get; set; } 62 } 63 }
测试的XML文件:
<?xml version="1.0" ?> <Books> <Book> <Title>CLR via C#</Title> <Author>Jeffrey</Author > <Price>95.00</Price> </Book> <Book> <Title>C++ Primer</Title> <Author>Stanley</Author > <Price>100.00</Price> </Book> </Books>
输出XML文件:
<?xml version="1.0" encoding="utf-8"?> <ArrayOfBook xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Book> <Price>100</Price> <Title>C#</Title> <Author>Lynn</Author> </Book> <Book> <Price>100</Price> <Title>J#</Title> <Author>Jason</Author> </Book> </ArrayOfBook>