views:

496

answers:

1

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)

    }
}
+4  A: 

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).

Cheeso
Re the last point: ReadSubtree: http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.readsubtree.aspx
Marc Gravell
ReadSubTree, cool! I learned something new!
Cheeso