Why is XML declaration ommitted in XmlMediaTypeFormatter?

Topics: ASP.NET Web API
Feb 14, 2013 at 3:17 PM
I was just wondering why XmlMediaTypeFormatter (when using default DataContractSerialized) is not emitting xml declaration?

I mean I know why it is not emitting it (the OmitXmlDeclaration in XmlWriterSettings has been set to true), but why is this a "good thing" and why is there no way to "turn it on" (like there is for indentation and max depth)...
Just curious....

Thanks
Z
Feb 20, 2013 at 5:12 PM
Bump. I agree. Where are the options to turn on the declaration?
Coordinator
Feb 28, 2013 at 4:47 AM
Can you tell us more about why including the XML declaration is important for your scenarios?

If including the XML declaration is required, then please create an issue in our Issue Tracker to expose this option. It should be a fairly straightforward change, so it might be a good candidate for a contribution from the community.
Oct 9, 2013 at 10:42 AM
Edited Oct 9, 2013 at 11:16 AM
It's important because I've seen client code depend on the presence of the xml declaration to detect xml.

I have created an issue: https://aspnetwebstack.codeplex.com/workitem/1330

What's the workaround to get the xml declaration included in the response? It seems hard to subclass XmlMediaTypeFormatter, it's not designed for that - relevant method uses lots of internal helper classes and private methods.

Is this fixed already? Seems like there's a WriterSettings property in the latest code:
https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Net.Http.Formatting/Formatting/XmlMediaTypeFormatter.cs When is this likely to be available?
Oct 9, 2013 at 11:38 AM
I have a dirty workaround here:

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;

namespace Web.App_Start
{
public class XmlWithDeclMediaTypeFormatter: XmlMediaTypeFormatter
{
    public XmlWithDeclMediaTypeFormatter()
    {
        UseXmlSerializer = true;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
        TransportContext transportContext)
    {
        WriteXmlDeclaration(writeStream);
        return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
    }

    private static void WriteXmlDeclaration(Stream writeStream)
    {
        const string XmlDeclaration = "<?xml version=\"1.0\"?>";
        var declBytes = Encoding.UTF8.GetBytes(XmlDeclaration);
        writeStream.Write(declBytes, 0, declBytes.Length);
    }
}
}