Proper way to implement IXmlSerializable?

Yes, GetSchema() should return null.

IXmlSerializable.GetSchema Method This
method is reserved and should not be
used. When implementing the
IXmlSerializable interface, you should
return a null reference (Nothing in
Visual Basic) from this method, and instead,
if specifying a custom schema is
required, apply the
XmlSchemaProviderAttribute to the
class.

For both read and write, the object element has already been written, so you don’t need to add an outer element in write. For example, you can just start reading/writing attributes in the two.

For write:

The WriteXml implementation you
provide should write out the XML
representation of the object. The
framework writes a wrapper element and
positions the XML writer after its
start. Your implementation may write
its contents, including child
elements. The framework then closes
the wrapper element.

And for read:

The ReadXml method must reconstitute
your object using the information that
was written by the WriteXml method.

When this method is called, the reader
is positioned at the start of the
element that wraps the information for
your type. That is, just before the
start tag that indicates the beginning
of a serialized object. When this
method returns, it must have read the
entire element from beginning to end,
including all of its contents. Unlike
the WriteXml method, the framework
does not handle the wrapper element
automatically. Your implementation
must do so. Failing to observe these
positioning rules may cause code to
generate unexpected runtime exceptions
or corrupt data.

I’ll agree that is a little unclear, but it boils down to “it is your job to Read() the end-element tag of the wrapper”.

Leave a Comment