The XML Serializer built into the .Net framework is a pretty cool side-utility when working with anything that consumes XML. A few years ago I posted about how your should Make your XML strongly-typed: Because you can and it’s easy in which I discussed how easy and awesome it is to use the XSD.exe tool to quickly convert an XML file into a XSD and then further covnert into a Serializable c# class file. The only not-so-perfect part of using the XML Serializer is that it by default adds namespace and schema attributes that point at the W3C standard declarations – but it’s just as easy to remove these so your resulting XML looks perfectly like your original XML file.
Example .Net Framework Serializer Output
<?xml version="1.0" encoding="utf-16"?> <rootElement xmlns:xsi="http:=//www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> </rootElement>
In the above example, the class I have serialized actually makes no reference to the schema or schema instance to apply, but the .Net Framework trying to be o-so-cool has decided to put in the default W3C schema elements.
Notice the xmlns:xsi and xml:xsd tags?
When creating files that need to exactly match an output file (such as when you are using my previous post to replicate an XML file for serialization), this doesn’t help at all.
As with most niggling issues like this, there is an easy, simple way to remove these un-needed elements, and you won’t lose any sleep implementing them.
The Fix
An example usage of an XML Serializer in .Net looks quite similar to the below piece of code:
XmlSerializer s = new XmlSerializer(typeof(T)); StringWriter myWriter = new StringWriter(); s.Serialize(myWriter, myObject);
The MSDN documentation for the XmlSerializer shows a number of different overloads for the .Serialize() method, and one of them takes a list of namespaces and applies them to the output – this is exactly what we want to use in our case, as we want to specify them to be empty – for this, we use the overload listed here.
Taking the above and applying it to our goal of having no namespaces of schemas, we will send the serializer a namespace but make it empty.
This makes our solution’s code looks like this:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("",""); XmlSerializer s = new XmlSerializer(typeof(T)); StringWriter myWriter = new StringWriter(); s.Serialize(myWriter, myObject, ns);
And our resulting XML looks like:
<?xml version="1.0" encoding="utf-16"?> <rootElement> </rootelement>
Done!