混合 .Net Xml 序列化和自定义 xml 序列化

Mix .Net Xml Serialization and custom xml serialization

是否可以将 xml 中的 .net framework 序列化与一些手工序列化方法混合使用?

我有一个 "sealed" class Outline,其中包含一个我想使用的方法 WriteToXml()

更难,我有另一个 class 其中包含:

class Difficult
{

    [XmlElement("Point", typeof(Point))]
    [XmlElement("Contour", typeof(Outline))]
    [XmlElement("Curve", typeof(Curve))]
    public object Item;
}

对应一个xsi:choice。

CurvePoint 应该使用标准方法序列化,我想告诉序列化程序在 Item 是 [=13 时使用 WriteToXml() =].

如果点、轮廓和曲线都共享除对象之外的公共基础 class,您可以使用自定义 SerializationWrapper。试试这个:

public class DrawnElement {}
public class Point : DrawnElement {}
public class Curve : DrawnElement {}
public class Outline : DrawnElement
{
    public string WriteToXml()
    {
        // I assume that you have an implementation already for this
        throw new NotImplementedException();
    }
}

public class Difficult
{
    [XmlElement(typeof(DrawnElementSerializationWrapper))]
    public DrawnElement Item;
}

public class DrawnElementSerializationWrapper : IXmlSerializable
{

    private DrawnElement item;

    public DrawnElementSerializationWrapper(DrawnElement item) { this.item = item; }

    public static implicit operator DrawnElementSerializationWrapper(DrawnElement item) { return item != null ? new DrawnElementSerializationWrapper(item) : null; }

    public static implicit operator DrawnElement(DrawnElementSerializationWrapper wrapper) { return wrapper != null ? wrapper.item : null; }

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

    public void ReadXml(System.Xml.XmlReader reader)
    {
        // read is not supported unless you also output type information into the xml
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        var itemType = this.item.GetType();

        if (itemType == typeof(Outline))    writer.WriteString(((Outline) this.item).WriteToXml());
        else                                new XmlSerializer(itemType).Serialize(writer, this.item);
    }

}