Search code examples
wcfxml-serializationdatacontractserializer

WCF data contract serialization with custom XML attribute


Is there a possibility to get the response as the following since in my experience using data contracts does not allow to add an id inside an element (e.g. ). Is there a way to achieve the following structure? Also notice that this is without a root tag.

<Number Id=”1”> 
<FName>1234567890ABC</ FName >
<Date>7/1/2012 12:00:00 </ Date >
</Number >
< Number Id=”2”> 
< FName >9876543210XYZ</ FName >
< Date >7/1/2012 12:00:00 </ Date >
</ Number >

Thank you very much in advance.


Solution

  • from this post: How can you control .NET DataContract serialization so it uses XML attributes instead of elements?

    . . . take a look at XmlSerializerFormatAttribute which allows you to use the XmlSerializer for serialization.

    and from same post

    You can do this with the DataContractSerializer - the answer is to take over the Xml serialization yourself by implementing the IXmlSerializable interface. ...

    This article can be also helpful: http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/