让Dicionary<TKey,TValue>实现xml序列化与反序列化--继承IXmlSerializerable接口

使用XmlSerializer类来对自定义类进行序列化与反序列化存在一个问题,这个问题就是它不能序列化与反序列化,类型为Dicionary的成员。

我设计了一个类叫做SerializerDictionay,这个类即实现了Dictionay的所有功能,也能让其可以进行XML序列化与反序列化。

**核心思想:继承IXmlSerializerable接口,继承Dictionay
**

using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
public class SerializerDictionay<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        //用于返回结果的方法 直接返回null即可
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        //跳过根节点头部
        reader.Read();
        //键翻译机器
        XmlSerializer xsKey = new XmlSerializer(typeof(TKey));
        //值翻译机器
        XmlSerializer xsValue = new XmlSerializer(typeof(TValue));
        //判断当前不是元素节点 就进行反序列化
        while(reader.NodeType!=XmlNodeType.Element)
        {
            //反序列化键
            TKey key = (TKey)xsKey.Deserialize(reader);
            //反序列化值
            TValue value = (TValue)xsValue.Deserialize(reader);
            //存储到字典中
            this.Add(key, value);
        }
        //跳过根节点的尾部
        reader.Read();
    }

    public void WriteXml(XmlWriter writer)
    {
        //键翻译机器
        XmlSerializer xsKey = new XmlSerializer(typeof(TKey));
        //值翻译机器
        XmlSerializer xsValue = new XmlSerializer(typeof(TValue));
        
        //迭代器遍历,将键和值依次序列化
        foreach(KeyValuePair<TKey,TValue> kv in this)
        {
            xsKey.Serialize(writer, kv.Key);
            xsValue.Serialize(writer, kv.Value);
        }
    }
}

测试:

using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class TestLession4
{
    public int test4;
    public SerializerDictionay<int, string> dic;
}
public class Lession4 : MonoBehaviour
{
    void Start()
    {
        //序列化测试
        TestLession4 tl4 = new TestLession4();
        tl4.dic = new SerializerDictionay<int, string>();
        tl4.dic.Add(1, "111");
        tl4.dic.Add(2, "222");
        tl4.dic.Add(3, "333");
        string path = Application.persistentDataPath + "/TestLession4.xml";
        //输出路径方便查看 序列化好的xml文件
        print(path);
        using (StreamWriter sw = new StreamWriter(path))
        {
            XmlSerializer xr = new XmlSerializer(typeof(TestLession4));
            xr.Serialize(sw, tl4);
        }

        //反序列化测试
        using (StreamReader sr = new StreamReader(path))
        {
            XmlSerializer xs = new XmlSerializer(typeof(TestLession4));
            //Deserialize()方法返回值为object 里氏替换成TestLession4类型
            tl4= xs.Deserialize(sr)as TestLession4;
        }
    }
}

结果截图:
让Dicionary<TKey,TValue>实现xml序列化与反序列化--继承IXmlSerializerable接口_第1张图片

你可能感兴趣的:(xml序列化与反序列化,xml,数据持久化)