DataContract XML serialization and XML attributes

Schultz9999 picture Schultz9999 · Feb 1, 2011 · Viewed 65.7k times · Source

Is it possible to deserialize this XML into an object marked with the DataContract attribute?

<root>
<distance units="m">1000</distance>
</root>

As you may see there is "units" attribute. I don't believe that's supported. Or am I wrong?

Answer

Greg Sansom picture Greg Sansom · Feb 1, 2011

This can be achieved, but you will have to override the default serializer by applying the [XmlSerializerFormat] attribute to the DataContract. Although it can be done, this does not perform as well as the default serializer, so use it with caution.

The following class structure will give you the result you are after:

using ...
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Xml.Serialization;

[DataContract]
[XmlSerializerFormat]
public class root
{
   public distance distance=new distance();
}

[DataContract]
public class distance
{
  [DataMember, XmlAttribute]
  public string units="m";

  [DataMember, XmlText]
  public int value=1000;
}

You can test this with the following code:

root mc = new root();
XmlSerializer ser = new XmlSerializer(typeof(root));
StringWriter sw = new StringWriter();
ser.Serialize(sw, mc);
Console.WriteLine(sw.ToString());
Console.ReadKey();

The output will be:

<?xml version="1.0" encoding="utf-16"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <distance units="m">1000</distance>
</root>