在复杂对象图上使用IXmlSerializable接口

时间:2010-07-02 15:27:58

标签: .net xml ixmlserializable xml-serialization

如果使用自定义XML序列化(IXmlSerialiable),则在包含具有 NOT 的组成复杂对象的属性的复杂对象上使用自定义{{1}接口,如何在IXmlSerializable方法中指定您希望反序列化器对这些子属性使用普通反序列化?

注意:类似于this question

1 个答案:

答案 0 :(得分:7)

IXmlSerializable实现起来有点乏味,因为它不是一种全有或全无的方法,因为你无法为普通的XML序列化选择子类型。但是,如果我理解正确,您可以通过为未实现XmlSerializer的类型手动创建IXmlSerializable来实现您的目标。

例如,如果我们从两个类开始,Default没有实现IXmlSerializableCustom确实实现了它。

public class Default // Uses default XML Serialization
{
    public int Count { get; set; }
}

public class Custom : IXmlSerializable
{
    public int Count { get; set; }

    public XmlSchema GetSchema() { throw new NotImplementedException(); }

    public void ReadXml(XmlReader reader)
    {
        reader.ReadToDescendant("Count");
        this.Count = reader.ReadElementContentAsInt();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement("Custom");
        writer.WriteElementString("Count", this.Count.ToString());
        writer.WriteEndElement();
    }
}

然后我们创建第三个类Parent,它具有前面每个实例的子项,并以支持它的子项调用IXmlSerializable方法的方式实现ReadXml/WriteXml并创建另一个孩子的默认XML序列化程序。

public class Parent : IXmlSerializable
{
    public Parent()
    {
        this.Default = new Default { Count = 1 };
        this.Custom = new Custom { Count = 2 };
    }

    public Default Default { get; set; }
    public Custom Custom { get; set; }

    public XmlSchema GetSchema() { throw new NotImplementedException(); }

    public void ReadXml(XmlReader reader)
    {
        reader.ReadToFollowing("Custom");
        this.Custom = new Custom();
        this.Custom.ReadXml(reader);

        reader.ReadToFollowing("Default");
        var serializer = new XmlSerializer(typeof(Default));
        this.Default = (Default)serializer.Deserialize(reader);
    }

    public void WriteXml(XmlWriter writer)
    {
        this.Custom.WriteXml(writer);

        var ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        new XmlSerializer(typeof(Default)).Serialize(writer, this.Default, ns);
    }
}

要完成示例,请对Parent实例进行序列化和反序列化的示例程序:

static void Main()
{
    var sb = new StringBuilder();
    var serializer = new XmlSerializer(typeof(Parent));

    serializer.Serialize(new StringWriter(sb), new Parent());

    Console.WriteLine(sb);

    var parent = (Parent)serializer.Deserialize(new StringReader(sb.ToString()));

    Console.WriteLine("Parent.Custom.Count: {0}", parent.Custom.Count);
    Console.WriteLine("Parent.Default.Count: {0}", parent.Default.Count);
}