参考前面四篇文章,自己写的一个xml 序列化和反序列化的C#小例子 using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using System.Xml; using System.IO; [XmlRoot("Book")] public class Book { private string m_name; [XmlAttribute("Name")] public string Name { get { return m_name; } set { m_name = value; } } private int m_price; [XmlAttribute("Price")] public int Price { get { return m_price; } set { m_price = value; } } private string m_author; [XmlElement()] public string Author { get { return m_author; } set { m_author = value; } } private Page10 m_page10; [XmlElement("page10")] public Page10 Page { get { return m_page10; } set { m_page10 = value; } } } [XmlRoot("Page10")] public class Page10 { private int m_lines; [XmlElement("Lines")] public int Lines { get { return m_lines; } set { m_lines = value; } } private string m_color; [XmlElement("颜色")] public string Color { get { return m_color; } set { m_color = value; } } } namespace XmlSerialize { class Program { static void Main(string[] args) { Page10 page10 = new Page10(); page10.Color = "red"; page10.Lines = 100; Book book = new Book(); book.Author = "我"; book.Name = "bb"; book.Page = page10; book.Price = 30; //以文件形式 //TextWriter tr = new StreamWriter("test.xml"); //XmlSerializer sr = new XmlSerializer(typeof(Book)); //sr.Serialize(tr, book); //tr.Close(); //以文件形式序列化 MemoryStream stream = new MemoryStream(); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.GetEncoding("gb2312")); //XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); //writer.Formatting = Formatting.None; writer.Formatting = Formatting.Indented; XmlSerializer xs = new XmlSerializer(typeof(Book)); xs.Serialize(writer, book, ns); byte[] b = stream.ToArray(); //此处Trim一定要加上 string str = Encoding.GetEncoding("gb2312").GetString(b).Trim(); //string str = Encoding.UTF8.GetString(b).Trim(); Console.WriteLine(str); //反序列化 MemoryStream stream2 = new MemoryStream(b); XmlSerializer xs2 = new XmlSerializer(typeof(Book)); Book book2; book2 = (Book)xs2.Deserialize(stream2); } } }