Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use default XML serialization from within custom XML serialization methods

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)

    }
}
like image 789
Daniel Plaisted Avatar asked May 22 '09 14:05

Daniel Plaisted


1 Answers

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

like image 62
Cheeso Avatar answered Oct 06 '22 00:10

Cheeso