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

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

  • Comments 1
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

<TestID>0</TestID>
<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.

[XmlElement(ElementName="ID")]
public Int32 TestID;


After serialization, the XML contains

<ID>0</ID>

This same technique also works with the XmlAttribute attribute.

[XmlAttribute(AttributeName="ID")]
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">

Enjoy!,
-- DK

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