XmlMediaTypeFormatter not handeling DateTimeOffset properties?

Topics: ASP.NET Web API
May 14, 2012 at 8:13 PM

I am noticing that my resources with DateTimeOffset properties are showing nicely in JSON but not in XML...In XML I get an empty xml node for example: <DateSold />. Is anyone experiencing the same issue? Is there a but in XmlMediaTypeFormatter perhaps?


May 14, 2012 at 9:03 PM

The issue is probably with the XmlSerializer. Can you try configuring the XML formatter to use the DataContractSerializer instead?

Daniel Roth

May 14, 2012 at 10:46 PM


When I set it to use DataContractSerializer, I do get the value now but in two separate sub-nodes...

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseDataContractSerializer = true;

For example I get:

<DateSold xmlns:a="http://schemas.datacontract.org/2004/07/System">
What I am expecting is ISO 8601 string (which JsonFormatter does return) like so:
Is this a bug in Xml Formatter?
May 15, 2012 at 12:36 AM

That’s just how the DataContractSerializer serializes DateTimeOffsets. It’s not a bug.

If you want to do something different I think your only option is to write an IXmlSerializable wrapper around DateTimeOffset.

Daniel Roth

May 15, 2012 at 5:21 PM

But why is it not working by default? Meaning when DataContractSerializer is not used?

If DataContractSerializer is not used in XmlFormatter, should the output match that of JsonSerialized? In this case single xml node as stated above...

May 15, 2012 at 5:52 PM

Sadly our XML serialization story in .NET is not all it should be. Json.NET has a flexible converter story that gives you great control over how types like DateTimeOffset. The XML serializers in .NET just don’t have the same level of flexibility.

We are switching to use the DataContractSerializer by default, so that you at least get a reasonable consistent programming model for JSON and XML (based on Data Contracts), but there are still functional gaps between the two.

Daniel Roth

May 15, 2012 at 6:19 PM
Edited May 15, 2012 at 6:19 PM

I see....Thanks for the explanation.

You are correct in regards to Json.NET - I am using custom JsonNetCamelCaseFormatter for json output

I am even considering creating a custom Xml formatter that would use JsonConvert.DeserializeXmlNode( ) - perhaps I would get a consistent output...But then the binders may not work...Have not tried it:) Since I have luxury of using only Json I can remove xml formatter for now or just leave it as it using DataContractSerializer...


Again thanks for the explanation.