How can you control .NET DataContract serialization so it uses XML attributes instead of elements?

You can do this with the
DataContractSerializer – the answer is
to take over the Xml serialization
yourself by implementing the
IXmlSerializable interface. For
write-only support – you can leave the
implementation of ReadXml empty, and
return null for GetSchema, and then
write the implementation of WriteXml
as follows:

public class MyPerson : IXmlSerializable
{
  public string Name { get; set;}
  public string Email { get; set;}
  public string Phone { get; set;}

  public XmlSchema GetSchema() { return null; }
  public void ReadXml(XmlReader reader) { }
  public void WriteXml(XmlWriter writer)
  { 
    writer.WriteAttributeString("name", Name);
    writer.WriteAttributeString("email", Email);
    writer.WriteAttributeString("phone", Phone);
  } 
}

If you’re using the same type for, say, JSON serialization as well, then you are still free to add the DataContract and DataMember attributes – the DataContractSerializer will utilise the IXmlSerializable interface implementation only when writing Xml.

I blogged about this here.

Leave a Comment