2

Closed

Remove default namespaces from XML in Web API

description

The XML serialisation process injects default namespaces into the generated XML:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"  
These can be supressed in the XmlSerializer by explicitly passing in an XmlSerializerNamespaces object to the Serialize method.

I would be happy to develop a fix for this and submit a pull request if the team feel it is useful.
Closed Apr 5 at 6:53 PM by HongmeiG
The default namespaces should be harmless. Please let me know if this blocks you.

comments

HongmeiG wrote Sep 28, 2012 at 9:48 PM

We can add serializer settings to allow customization of this.

pierslawson wrote Sep 28, 2012 at 10:48 PM

Code I have used before is along the lines of below. It sets the default namespace to "" which clears the ambient namespaces... but if the object has an XmlRoot attribute with a namespace, it uses that. The resultant XML has the correct default namespace and no ambient namespaces.

var objectType = toBeSerialised.GetType();
var defaultNamespace = string.Empty;
var xmlRootAttributes = toBeSerialised.GetType().GetCustomAttributes(typeof(XmlRootAttribute), true) as XmlRootAttribute[];
if (xmlRootAttributes != null && xmlRootAttributes.Length > 0)
{
defaultNamespace = xmlRootAttributes[0].Namespace;
}

// Use this object to prevent the serilaizer from adding extra "Ambient" namespaces
var xmlSerializerNamespaces = new XmlSerializerNamespaces();
xmlSerializerNamespaces.Add(String.Empty, defaultNamespace);

var xmlSerializer = new XmlSerializer(objectType);

xmlSerializer.Serialize(xmlWriter, toBeSerialised, xmlSerializerNamespaces);

pierslawson wrote Apr 5 at 9:27 PM

True it is "mostly harmless" but

A) It is a waste of space
B) It confuses people consuming the service
C) It reveals to attackers extra details about the implementation of the service

Since it is so easy to fix, I'm disappointed.

pierslawson wrote Apr 5 at 10:14 PM

Sorry, my last comment was harsh! I'll look into it myself and see if I can't supply a potential fix.

Thanks for looking at it.

adrianp74 wrote Apr 9 at 12:34 AM

With all the posts and people searching on how to do this I'd hardly call it harmless. Obviously it causes a lot of issues for people. Suppressing it should be a lot easier that having to right custom serializers. I find myself having to remove it a lot more than needing it there.

pierslawson wrote Apr 9 at 7:28 AM

I hope to submit a pull request for this in the next few days.