UD2SL3——lXmlSerialzable接口
本章代码关键字
1 2 3 4 5 6 7 8 9 10 11 12 13 IXmlSerializable GetSchema() { } WriteXml(XmlWriter writer) { } writer.WriteAttributeString(,) writer.WriteElementString() writer.WriteStartElement() writer.WriteEndElement() ReadXml(XmlReader reader) { } reader[] reader.Read() reader.Value reader.ReadStartElement() reader.ReadEndElement()
lXmlSerialzable接口
C# 的 XmlSerializer
提供了可拓展内容
可以让一些不能被序列化和反序列化的特殊类能被处理
让特殊类继承 IXmlSerializable
接口 实现其中的方法即可
自定义类实践
序列化回顾
1 2 3 4 5 6 7 8 9 10 11 12 13 14 TestLesson3 t = new TestLesson3(); t.test2 = "123" ; using (StreamWriter writer = new StreamWriter(Application.persistentDataPath + "/TestLesson3.xml" )){ XmlSerializer s = new XmlSerializer(typeof (TestLesson3)); s.Serialize(writer, t); } using (StreamReader reader = new StreamReader(Application.persistentDataPath + "/TestLesson3.xml" )){ XmlSerializer s = new XmlSerializer(typeof (TestLesson3)); t = s.Deserialize(reader) as TestLesson3; }
自定义类的自定义序列化
若要自定义自己的序列化规则,需要继承IXmlSerializable
接口
这样XML序列化对象 在序列化 该类的对象 时 会调用该接口的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class TestLesson3 : IXmlSerializable { public int test1; public string test2; public XmlSchema GetSchema () { return null ; } public void ReadXml (XmlReader reader ) { } public void WriteXml (XmlWriter writer ) { } }
序列化时会自动调用的方法
在该方法里一定会使用参数writer
的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public void WriteXml (XmlWriter writer ){ writer.WriteAttributeString("test1" , test1.ToString()); writer.WriteAttributeString("test2" , test2); writer.WriteElementString("test1" , test1.ToString()); writer.WriteElementString("test2" , test2); XmlSerializer s = new XmlSerializer(typeof (int )); writer.WriteStartElement("test1" ); s.Serialize(writer, test1); writer.WriteEndElement(); XmlSerializer s2 = new XmlSerializer(typeof (string )); writer.WriteStartElement("test2" ); s2.Serialize(writer, test2); writer.WriteEndElement(); }
反序列化时会自动调用的方法
在该方法里一定会使用参数reader
的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 public void ReadXml (XmlReader reader ){ test1 = int .Parse(reader["test1" ]); test2 = reader["test2" ]; reader.Read(); reader.Read(); test1 = int .Parse(reader.Value); reader.Read(); reader.Read(); reader.Read(); test2 = reader.Value; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "test1" : reader.Read(); test1 = int .Parse(reader.Value); break ; case "test2" : reader.Read(); test2 = reader.Value; break ; } } } XmlSerializer s = new XmlSerializer(typeof (int )); XmlSerializer s2 = new XmlSerializer(typeof (string )); reader.Read(); reader.ReadStartElement("test1" ); test1 = (int )s.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("test2" ); test2 = s2.Deserialize(reader).ToString(); reader.ReadEndElement(); }
返回框架
一般用不到,直接返回空
1 2 3 4 public XmlSchema GetSchema (){ return null ; }