嵌套/子对象的自定义Xml序列化

时间:2010-02-05 17:53:45

标签: c# ixmlserializable

我有一个场景,其中我有一个类Resource,其中有两个嵌套在其中的类; Action和ResourceURL。我需要为Resource和Action编写自定义xmlserializer,而不是为ResourceURL编写。我为两者实现了IXmlSerializable。

问题是,当Resource被序列化时,我调用Action.WriteXML(XmlWriter)来获取Action的序列化形式,但是我无法获得ResourceURL的序列化形式。标签变得混乱,并且还添加了标签。

那么我如何序列化一个对某些嵌套对象进行客户seril化而不为其他对象进行sercel化的对象呢?

1 个答案:

答案 0 :(得分:19)

以下是WriteXml方法示例:

    void IXmlSerializable.WriteXml(XmlWriter writer)
    {
        // Simple string value:
        writer.WriteAttributeString("Name", this.Name);

        // Object without IXmlSerializable implementation:
        writer.WriteStartElement("NonCustomObject");
        new XmlSerializer(NonCustomObjectType).Serialize(writer, this.NonCustomObject);
        writer.WriteEndElement();

        // Object with IXmlSerializable implementation:
        writer.WriteStartElement("CustomObject");
        (this.CustomObject as IXmlSerializable).WriteXml(writer);
        writer.WriteEndElement();
    }

这是一个相应的ReadXml方法:

    void IXmlSerializable.ReadXml(XmlReader reader)
    {
        // Simple string value
        this.Name = reader.GetAttribute("Name");

        // Object without IXmlSerializable implementation here:
        reader.ReadStartElement();
        if (reader.Name == "NonCustomObject")
        {
            reader.ReadStartElement();
            this.NonCustomObject = new XmlSerializer(NonCustomObjectType).Deserialize(reader);
            reader.ReadEndElement();
        }

        // Object with IXmlSerializable implementation here:
        reader.ReadStartElement();
        if (reader.Name == "CustomObject")
        {   
            (this.CustomObject as IXmlSerializable).ReadXml(reader);
            reader.ReadEndElement();
        }
    }