Quick Tip: Serializing an Object Field as an XML Attribute

The addition of the XML Serializer is one of the reasons I really love version 2 of the .NET Compact Framework.  I use the XML Serializer in very nearly every application I write; to save application state, data files, etc.  By default, the XML Serializer will create a child node for every field in a type.  For example, the following object

public class TestData{    public Int32 TestID;    public String Description;}

becomes

<TestData xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema">  <Description>Sample test description.</Description>  <TestID>0</TestID></TestData>

There are times that you may wish to serialize one or more fields as attributes on the object's node (ex: reduce the size of the XML).  By decorating the TestID field with an XmlAttribute attribute, the TestID field

[XmlAttribute()]public Int32 TestID;

now becomes an attribute (highlighted in purple) on the TestData node.

<TestData xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema" TestID="0">  <Description>Sample test description.</Description></TestData>

Enjoy!
-- DK

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