6

如果使用自定义 XML 序列化 ( ),在包含使用自定义接口IXmlSerialiable的组成复杂对象的属性的复杂对象上,您如何在方法中指定您希望反序列化器对这些子属性使用普通反序列化?IXmlSerializableIXmlSerializable.ReadXml(XmlReader reader)

注意:类似于这个问题

4

1 回答 1

8

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);
}
于 2010-07-02T17:39:05.673 回答