Xml Serialization and the XmlArray and XmlArrayItem control attributes

We all know -or should know- that when using XML Serialization either over SOAP or manually, we can control the serialized output with so called control attributes.

Well known examples are the XmlElementAttribute and the XmlAttributeAttribute. I think it's worth mentioning the usefulness of the XmlArrayAttribute and the XmlArrayItemAttribute as well. XmlArrayAttribute to be used on the usual fixed arrays, since dynamic arrays can't be serialized and the XmlArrayItemAttribute for the element name of a single item in the array.

Here's a sample class:

using System.Xml.Serialization;
[Serializable]
public class Customer
{ // we need default ctor for Serialization!
public Customer()
{}
private string __fname;
private string __lname;
private Invoice[] __invoices;




[XmlElement("FirstName")]
public string FName
{
get { return this.__fname; }
set { this.__fname=value; }
}

[XmlElement("LastName")]
public string LName
{
get { return this.__lname; }
set { this.__lname=value; }
}

[XmlArray("Orders")]
[XmlArrayItem("Order")]
public Invoice[] Invoices
{
get { return this.__invoices; }
set { this.__invoices=value; }
}
}

Without taking into account that an Invoice is actually not the same as an Order :-), when we look at the serialized XML for a Customer object, it looks roughly like this:

<Customer>
 <FirstName>Wim</FirstName>
 <LastName>Hollebrandse</LastName>
 <Orders>
  <Order>
   <ID>12312</ID>
  </Order>
  <Order>
   <ID>12313</ID>
  </Order>
  <Order>
   <ID>12314</ID>
  </Order>
 </Orders>
</Customer>

Oops - just noticed I typed 'ID' with two capitals. Check out the discussion on Andrew Stevenson's blog.

6 Comments

Comments have been disabled for this content.