XMLSerializer - Removing Namespace & Schema Declarations xmlns:xsi xml:xsd
Join the DZone community and get the full member experience.
Join For Freethe 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><span color="blue" style=""> </span>
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!
Published at DZone with permission of Douglas Rathbone, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments