3

The problem:

I have created a WebApi and need to support XML.

The default DataContractSerializer generates namespaces like:

xmlns:d2p1="http://schemas.datacontract.org/2004/07/Vendor.App.Model.DeeperModel"
xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"

I don't want to have these namespaces in my XML. Its very hard to work with them.

In my case I need to support XLST from FileMaker, which has problems with namespaces other XLS Parsers do not have.

What I have found, but is not a duplicate for later statet reasons:

I have read about it here, here and other locations in the web.

I only found this two advices:

  • Use [DataContract(Namespace = "")]-Attribute
  • Use XmlSerializer
    • by extending XmlMediaTypeFormatter
    • by setting config.Formatters.XmlFormatter.UseXmlSerializer = true

DataContract:

DataContract Attribute does not work good for classes I have no control. I do not want to do this ugly hack:

[DataContract(Namespace = "")]
IThisIsNonesense<T> : IEnumerable<T>
{
}

[DataContract(Namespace = "")]
ThisIsNonesense<T> : List<T>, IThisIsNonesense<T>
{
    public ThisIsNonesense() : base() {}
}

XmlSerializer:

XmlSerializer is not very flexible. For example it does not support Interface. I make for example heavy use of IEnumerable<T>.

My Question:

How is it possible to remove all Namespaces by default, without making changes through the whole codebase? If it is not possible what would you advice?

Community
  • 1
  • 1
Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
  • I usually just parse the files myself using XDocument. – jdweng Jan 26 '17 at 10:41
  • While this would work, this would be way to much overhead for me. I don't want to loose the benefits of serialization. Also my api methods should be available via JSON and any other format that will show up in the future. @jdweng – Christian Gollhardt Jan 26 '17 at 10:53

1 Answers1

0

Take a look at the code in this answer which does use System.Xml.Linq but can be invoked to display in the console in one easy line:

Console.WriteLine(RemoveAllNamespaces(XElement.Parse(xml)).ToString());

However, you mention in your comment that you don't want to loose the benefits of serialization. If one of those benefits is deserialization, then I'd advise against this - it will result in a SerializationException being thrown by DataContractSerializer.

Finally, it seems you're interested in making your API methods able to support multiple media types. This is a stated ability of ASP.NET Web API, so if you're already using .NET, this could be a good option.

QA Collective
  • 2,222
  • 21
  • 34