Removing default namespaces from XML serialized .NET objects
Posted: (EET/GMT+2)
In .NET, the support for almost automatic serialization can become very handy. Of course, since XML is everywhere, it is also possible to serialize objects into XML based formats with the XmlSerializer class from the System.Xml.Serialization namespace. However, if you've ever used this class, you might have noticed that it creates automatic namespaces "xmlns:xsi" and "xmlns:xsd" into the documents, something which you might find unnecessary. For example, a simple StringBuilder object might be serialized as follows:
<?xml version="1.0"?> <StringBuilder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Capacity>16</Capacity> <Length>0</Length> </StringBuilder>
Now then, the question is, how would you strip out or remove these default namespaces? Of course, there are many possibilities, but if your needs are simple, you could use the XmlDocument class and the following snippet of simple C# code:
// create an object to serialize StringBuilder testObject = new StringBuilder(); // create xml serializer XmlSerializer xmlSerializer = new XmlSerializer(testObject.GetType()); // serialize to memory stream & load xml MemoryStream stream = new MemoryStream(); XmlDocument doc = new XmlDocument(); xmlSerializer.Serialize(stream, testObject); stream.Position = 0; doc.Load(stream); stream.Close(); // strip out default namespaces "xmlns:xsi" and "xmlns:xsd" doc.DocumentElement.Attributes.RemoveAll(); // save to file doc.Save(@"C:\Temp\Serialization Test.xml");
Here, the magic is done by the single call to "doc.DocumentElement.Attributes.RemoveAll". If you only have a single object serialized, the results will look like this:
<?xml version="1.0"?> <StringBuilder> <Capacity>16</Capacity> <Length>0</Length> </StringBuilder>
The only problem with this code is that if you have multiple objects to serialize, you would need to repeat the call to the RemoveAll method for all top-level elements. Good luck!