Is it possible to mix the .net framework serialization in xml with some handmade serialization method ?
I have a "sealed" class Outline
which contains a method WriteToXml()
that I would like to use.
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.
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
.
If Point, Outline, and Curve all share a common base class other than object, you could use a custom 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.