Controlling XML Serialization of Attributes

The default action, when serializing objects to XML, is for each public property and field to generate an XML element. The XmlAttribute attribute can be applied to public members to modify this behaviour and instead generate XML attributes.

XML Attributes

An XML attribute is a name / value pair that can be added to the opening tag of an XML element. It allows additional information to be included in an XML element. The following shows the opening tag of an element with two attributes. The attributes are named, "Name" and "Budget". Their values are provided in quotes.

<Department Name="IT" Budget="250000">

When you use the default settings for serializing objects to XML, the public properties and fields are represented as elements in the resultant XML. The object becomes a single element and each property is added as a child element. Where members with complex types are present, these may create nested elements.

Sometimes you may prefer that simple types are serialized as attributes of the object's root element. This can be achieved by decorating the properties with the XmlAttribute attribute. Members with complex types containing further properties cannot be serialized in this manner.

XmlAttribute

We will demonstrate the use of XmlAttribute by serializing an object to XML using a number of versions of the attribute. To begin, create the following class. This is a simplified version of the class used in the "Controlling Serialization of XML Elements" article. Review that article for the code that performs the serialization.

As every member in the class is now configured to be an XML attribute, the resultant XML contains a self-closing Department tag with two attributes.

<Department Name="IT" Budget="250000" />

Setting Attribute Names

Sometimes you will want to change the name of the XML attribute so that the property name is not used. You can do so using the AttributeName parameter, which accepts a string containing the new name. In the example below the Name property's attribute has been renamed to "DepartmentName".

Specifying Attribute Namespaces

As with other parts of a serialized XML document, such as the root element or individual child elements, you can specify the namespace for each attribute. To do so, set the value of the Namespace parameter. When a namespace is applied to an attribute, a namespace prefix is required. The serializer automatically generates prefixes for each unique namespace used.

When serialized, the namespace is added to the root element and given a prefix automatically. In the XML below, the prefix is "d1p1". The attribute is modified to include the prefix to link it to the declared XML namespace.