A Note on XML Serialization

A coworker asked me recently how to serialize an array of objects, belonging to different classes deriving from the same base class, such that the XML elements representing these objects revealed the class they belong to. He wanted the XML to look like this:

<ArrayOfBase>
    <Derived1 />
    <Derived2 />
    <Derived1 />
    ...
</ArrayOfBase>

I remembered doing exactly that a while ago, but I couldn’t remember exactly what I did. But it wasn’t difficult for us and didn’t take long to find the answer. Here it is:

Class RowSet is a DTO (data transfer object) containing a matrix of data cells.

[Serializable]
public class RowSet {
    [XmlElement( ElementName = "row" )]
    public Row[] Rows { get; set; }
    ...
}

Note how the XmlElement attribute is applied to a collection. It defines serialization of individual elements rather than the collection itself. Row is defined as a one-dimentional array of abstract Cells.

[Serializable]
public class Row {
    [XmlElement( Type = typeof( DataCell ),
                 ElementName = "d" )]
    [XmlElement( Type = typeof( NullCell ),
                 ElementName = "n" )]
    public Cell[] CellArray { get; set; }
    ...
}

Cell is an abstract class and DataCell and NullCell derive from it. RowSet serialized into XML looks like this:

<rows>
    <row>
        <d value=... />
        <n />
        <n />
        <d ... />
        ...
    </row>
    <row>
        ...
    </row>
    ...
</rows>
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s