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

时间:2015-07-29 15:41:05

标签: c# xml-serialization

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

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

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

class Difficult
{

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

它对应于xsi:choice。

CurvePoint应使用标准方法序列化,我想告诉序列化程序在WriteToXml()Item时使用Outline

1 个答案:

答案 0 :(得分:0)

如果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);
    }

}