Serializing Generics

Lets say I want a generic list of something in XML:

e.g.

Public Property AccountNumbers As List(of String)

when we serialize this, the serializer helpfully defaults to the Type of the generic (in this case, string), so we would get the XML:

<AccountNumbers>
  <string>1234</string>
  <string>5678</string>
</AccountNumbers>

Which works but isn’t very reader friendly. If we want to change the <string> to something else, we decorate the property with the XmlArrayItem attribute:

<System.Xml.Serialization.XmlArrayItem("Account")> _
Public Property AccountNumbers As List(of String)

And so we get the nicely formatted result:

<AccountNumbers>
  <Account>1234</Account>
  <Account>5678</Account>
</AccountNumbers>

Advertisements

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 )

Google+ photo

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

Connecting to %s