Controlling Serialization of XML Elements

When serializing classes to XML, each public property and field value is transformed into an XML element. The name of the element matches the name of the property. The XmlElement attribute allows the names and formatting of XML tags to be modified.

XML Elements

An XML element generally consists of a start tag, an end tag and all of the information in between. This can include attributes within the opening tag and text or other child elements contained within the tags. In some cases a single, self-closing XML tag will define an element. The following is an example element:

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

When objects are serialized to XML using default settings, each public property and field with a non-null value is converted into an element within the XML's root element. The element's name matches the name of the property or field so that the XML can later be deserialized into a new object with the original values. Null properties are not converted to elements; they are simply omitted. Sometimes it is necessary to override this behaviour to achieve modified results.

In this article we will examine the XmlElement attribute, which provides control over the output of XML for properties and fields.

XmlElement

We can demonstrate the use of the XmlElement attribute by creating some sample objects, serializing them to disk and viewing the generated XML. To begin, we need a class to serialize. The following class represents a department within a business, with properties for the department name and budget.

If you execute the code, the XML file will contain information similar to that shown below. For clarity, the opening xml tag and default namespaces have been removed.

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

Controlling Element Names

It is common to change the element names for individual properties. You can do so by decorating the appropriate member with the XmlElement attribute and the ElementName named parameter. The new name is provided as the parameter's value.

Modify the Department class as follows to give the two properties custom element names: