Quick Tip: Specifying a field’s name when using the XmlSerializer

Last month, I wrote about how to instruct the XmlSerializer to create an XML attribute for fields in an object.  Today, I'd like to talk about how to specify the name used to represent a field in the resulting XML.

By default, when an object is serialized, fields are serialized into nodes with names that match the name of the field.  When an instance of the example TestData object(below) is serialized

public class TestData
    public Int32 TestID;
    public String Description;

the TestID and Description fields become

<Description>Sample test description.</Description>

At times, it may be desirable to change the default naming behavior.  To change the name, we decorate the TestID field with an XmlElement attribute.

public Int32 TestID;

After serialization, the XML contains


This same technique also works with the XmlAttribute attribute.

public Int32 TestID;

Creates an attribute called ID (highlighted in purple) in the TestData node.

<TestData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ID="0">

-- DK

This posting is provided "AS IS" with no warranties, and confers no rights.

Skip to main content