刚开始看XML序列化时,看到[XmlAttribute]、[XmlElement]不知道怎么用,只是简单的将一个类序列化。而对于一些复杂的配置文件,通常是通过拼字符串的形式生成XML文件,后来偶尔的一次机会,发现完全可以通过设置让XML自动序列化成我们想要的XML文件格式。
首先定义一个类:
首先定义一个类:
[XmlRoot("我是中国人")] public class People { [XmlAttribute("家乡")] public string Home = ""; [XmlElement("姓名")] public string Name = ""; [XmlElement("年龄")] public string Sex = ""; public int Age = 100; }然后就可以将这个类进行XML序列化:
XmlSerializer xs = new XmlSerializer(obj.GetType());//typeof() Stream sm = new FileStream(sFullFileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); //设置头 XmlTextWriter xmltw = new XmlTextWriter(sm, Encoding.GetEncoding("GB2312")); xmltw.WriteRaw(""); XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces(); xmlns.Add("", ""); xs.Serialize(xmltw, obj, xmlns); sm.Close();反序列化比较简单:
XmlSerializer xs = new XmlSerializer(typeof(class)); Stream sm = new FileStream(sFullFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); object obj = xs.Deserialize(sm) as class; sm.Close();