简体   繁体   English

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

[英]Mix .Net Xml Serialization and custom xml serialization

Is it possible to mix the .net framework serialization in xml with some handmade serialization method ? 是否可以将xml中的.net框架序列化与某些手工序列化方法混合在一起?

I have a "sealed" class Outline which contains a method WriteToXml() that I would like to use. 我有一个“密封的”类Outline ,其中包含我想使用的方法WriteToXml()

More difficult, I have another class which contains : 更加困难的是,我还有另一个包含以下内容的类:

class Difficult
{

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

It corresponds to a xsi:choice. 它对应于xsi:choice。

Curve and Point should be serialized using the standard method, and I would like to tell the serializer to use WriteToXml() when Item is an Outline . CurvePoint应该使用标准方法进行序列化,并且我想告诉序列化程序在ItemOutline时使用WriteToXml()

If Point, Outline, and Curve all share a common base class other than object, you could use a custom SerializationWrapper. 如果“点”,“轮廓”和“曲线”都共享除对象之外的公共基类,则可以使用自定义的SerializationWrapper。 Try this: 尝试这个:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM