I have a class in .NET that implements IXmlSerializable. I want to serialize its properties, but they may be complex types. These complex types would be compatible with XML serialization, but they don't implement IXmlSerializable themselves. From my ReadXml and WriteXml methods, how do I invoke the default read/write logic on the XmlReader/XmlWriter that is passed to me.
Perhaps code will make it clearer what I want:
public class MySpecialClass : IXmlSerializable
{
public List<MyXmlSerializableType> MyList { get; set; }
System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
{
// Read MyList from reader, but how?
// Something like this?
// MyList = (List<MyXmlSerializableType>)
reader.ReadObject(typeof(List<MyXmlSerializableType>));
}
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
// Write MyList to writer, but how?
// Something like this?
// writer.WriteObject(MyList)
}
}
For the writer, you could just create an XmlSerializer for the MySerializableType, then serialize the list through it to your writer.
void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
{
// write xml decl and root elts here
var s = new XmlSerializer(typeof(MySerializableType));
s.Serialize(writer, MyList);
// continue writing other elts to writer here
}
There is a similar approach for the reader. EDIT: To read only the list, and to stop reading after the List is complete, but before the end of the stream, you need to use ReadSubTree (credit Marc Gravell).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With