C#实现接口xml序列化与反序列化

C#中接口无法被xml序列化,提示不支持。百度和bing也搜不到,只好自己动手写了

原理上肯定支持,.Net自己的xml序列化有一个IXmlSerializable接口。

自行实现该接口,并取得实现改接口的类,再进行自定义的序列化处理即可。

 

using System.Collections;
using System.Xml.Serialization;
using System;
using System.Xml;

[XmlRoot("SerInterface"), Serializable]
public class SerInterface<TInterface> : IXmlSerializable
{
    public TInterface Source { get { return (TInterface)mSource; } }
    string mTypeName;
    object mSource;


    public SerInterface()
    {

    }

    public SerInterface(object interfaceObj)
    {
        this.mSource = interfaceObj;
        mTypeName = mSource.GetType().FullName;
    }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        var typeSer = new XmlSerializer(typeof(string));
        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();

        if (wasEmpty)
            return;
        while (reader.NodeType != XmlNodeType.EndElement)
        {
            reader.ReadStartElement("Type");
            mTypeName = typeSer.Deserialize(reader) as string;

            reader.ReadEndElement();

            var sourceSer = new XmlSerializer(Type.GetType(mTypeName));
            reader.ReadStartElement("Object");
            mSource = sourceSer.Deserialize(reader);
            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    public void WriteXml(XmlWriter writer)
    {
        var typeSer = new XmlSerializer(typeof(string));
        var sourceSer = new XmlSerializer(mSource.GetType());

        writer.WriteStartElement("Type");
        typeSer.Serialize(writer, mTypeName);
        writer.WriteEndElement();
        writer.WriteStartElement("Object");
        sourceSer.Serialize(writer, mSource);
        writer.WriteEndElement();
    }
}

 

 

使用:

//把接口嵌套
IXXX tmp = new Class1();
var serInterface = new SerInterface<IXXX>(tmp);


//序列化
var xmlSer = new XmlSerializer(serInterface.GetType());
var writer = new MemoryStream();

xmlSer.Serialize(writer, serInterface);

StreamReader sr = new StreamReader(writer);
var serStr = Encoding.UTF8.GetString(writer.ToArray());

writer.Flush();
writer.Close();
sr.Close();


//反序列化
xmlSer = new XmlSerializer(typeof(SerInterface<IXXX>));
TextReader reader = new StringReader(serStr);
var deSer =  xmlSer.Deserialize(reader);

//原始数据
var sourceInterfaceData = (deSer as SerInterface<IXXX>).Source;

 

C#实现接口xml序列化与反序列化

上一篇:20141214--C#父类,子类


下一篇:WPF:完美自定义MeaagseBox 2.0