I need a way to customize C# XML (de)serialization mechanism in this way:
[Serializable]
public class MyElement : IXmlSerializable
{
[XmlAttribute]
public string PropertyX { get; set; }
[XmlElement]
public MySubElement SubElement { get; set; }
// .... other properties and elements...
[XmlIgnore]
public string ElementXml { get;set; }
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
// use default deserialization mechanism, like IXmlSerializable isn't implemented
}
public void WriteXml(XmlWriter writer)
{
if (!string.IsNullOrEmpty(ElementXml)) {
// serialize as ElementXml value
}
else
{
// serialize using default serialization mechanism, like IXmlSerializable isn't implemented
}
}
}
I need to use this paradigm on multiple elements, for instance MySubElement should also behave like this. Object model is complex, so implementing this attribute by attribute or element by element isn't an option for me. Can this be done?