Some colleagues of mine wanted to supported REST services that also include attributes, and not only elements.
However, WCF data contracts by default do not support serializing attributes. However, there is an attribute that enables the "old fashioned" XmlSerializer support in WCF Data Contracts to make this work.
The XmlSerializerFormat attribute should be added to your Service Contract, and Presto! : attribute support.
See the code sample below.
    [ServiceContract]
    [XmlSerializerFormat]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate="composite")]
        CompositeType GetComposite();
    }
    [DataContract]
    public class CompositeType
    {
        [DataMember]
        [XmlAttribute]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }
        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
The resulting XML then looks like this:
<?xml version="1.0" encoding="utf-8"?>
<CompositeType BoolValue="true" lang=”EN-US”>="http://www.w3.org/2001/XMLSchema-instance" lang=”EN-US”>="http://www.w3.org/2001/XMLSchema">
            <StringValue>testvalue</StringValue>
</CompositeType>
4 comments
Very cool solution Raimond! And the attributes will be ignored when you use JSON instead of XML.
I’m glad you picked up the challenge sander and I offered 😛
willemm
please let me know how to use [XmlSerializerFormat]
for CollectionDataContract
srinivas
Hi srinivas, as te XmlSerializerFormat turns on “old-school” XmlSerializer behavior, you should use the attributes associated with that. In this case the XmlRootAttribute:
[CollectionDataContract(Name=”Customers”, ItemName=”Customer”)]
[XmlRoot(ElementName=”Customers”)]
public class CustomerCollection : Collection
{
}
Raimondb
Great Article!
You saved my day.
andreas m