Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
Now let’s put the pieces together and see how we can override
hard coded serialization attributes. Imagine our parking lot application sends
updates about the parked cars to interested parties in an XML format. For some
reason there is one client who needs the data in a slightly different format.
Instead of writing an entire different set of classes to produce the custom
format we simply customize the ones we already have to change the element names
for ParkingLot and Car objects.
The example starts out by instantiating two XmlAttributes
collections, one for the attributes for ParkingLot class, another one to apply
attributes to the Cars field.
Next, we assign an XmlRootAttribute object to the XmlRoot
property to change the root element name for ParkingLot objects.
Then we change the element name for a Car item in the Cars
ArrayList to “ParkedCar” by assigning an XmlArrayItemAttribute to XmlArrayItems
property.
Finally, we call the overloaded Add() method to add the two
XmlAttributes objects to an XmlOverrides object.
Now the XmlOverrides object is set up and we can pass it to to
the constructor of the XmlSerializer.
5
Listing 10.1: Serialization using attribute overrides
public static void SerializeCustomParkingLot(XmlWriter writer,
ParkingLot parkingLot)
{
XmlAttributes
carsAttributes = new XmlAttributes();
XmlAttributes classAttributes
= new XmlAttributes();
classAttributes.XmlRoot
= new
XmlRootAttribute("ParkingLotRoot");
carsAttributes.XmlArrayItems.Add( new
XmlArrayItemAttribute("ParkedCar", typeof(Car)));
XmlAttributeOverrides
overrides = new XmlAttributeOverrides();
The output of the Serialize() method (Listing 10.2) shows that
XML nodes corresponding to items in the ArrayList “Cars” are now named
“ParkedCar” as specified by the XmlArrayItem attribute. The XmlRootAttribute
applied to the ParkingLot class changes the name of the root node from
ParkingLot to “ParkingLotRoot”.
6
Listing 10.2: A
serialized ParkingLot object with and without the overriding attributes from
Listing 10.1