10

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)

    }
}
2
  • Daniel, do you have more questions on this? I think you've been given the answer. Commented Jul 26, 2009 at 15:40
  • The ReadSubtree method was the key to solving the problem. I haven't marked the current answer as accepted because it doesn't explain exactly how to do this. Commented Jul 29, 2009 at 17:57

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

Re the last point: ReadSubtree: msdn.microsoft.com/en-us/library/…
Is the XmlSerializer instance lightweight enough to be instantiated on every call like this, or should it be cached?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.