Prevent .NET WCF Web Service from adding namespace to every element

You've created a .NET WCF webservice, it returns XML (blech) and for some reason it's adding xmlns="" to every single element instead of just the Root element like you intended, making things even uglier than "normal" XML.

This happened to me when I generated my classes using the .NET tool xsd.exe by running it against my source schemas. It's a very handy way of generating useful (yet behemoth) classes from just an .xsd file.

It then creates a <yourSchema>.cs file that you can include in your VS solution. The problem is, by default it adds one single attribute to the root element of the class. In my case it looked like so:

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.6.1064.2")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "urn:hl7-org:v3")]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:hl7-org:v3", IsNullable = false)]
    public partial class PRPM_IN406010UV : PRPM_IN406010UVMCCI_MT000100UV01Message

See the attribute that says: [System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:hl7-org:v3", IsNullable = false)]

That's the issue! IsNullable = false. That means the elements are all going to have a namespace attribute. Sometimes xsd.exe doesn't add this attribute at all, which means it still creaetes all the namepace atrributes.

To fix it

If the class attribute already exists, change IsNullable to true, or simple add the following attribute:

[System.Xml.Serialization.XmlRootAttribute(Namespace = "<yourNamespace>", IsNullable = true)]

Boom, done.