混合.net Xml序列化和自定义Xml序列化

本文关键字:序列化 Xml 自定义 net 混合 | 更新日期: 2023-09-27 18:05:18

是否有可能将。net框架序列化与一些手工序列化方法混合在xml中?

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

更难,我有另一个类包含:

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

对应于xsi:choice。

CurvePoint应该使用标准方法序列化,当ItemOutline时,我想告诉序列化器使用WriteToXml()

混合.net Xml序列化和自定义Xml序列化

如果Point, Outline和Curve都共享一个公共基类而不是object,则可以使用自定义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);
    }
}
相关文章: