Deserialize XML Namespaces

When deserializing XML document using the System.Xml.Serialization.XmlSerializer, the XML Namespaces Attribute(s) cannot be hydrated using XmlAttribute attribute.

There is a designated class XmlSerializerNamespaces that needs to be used. Without this, you would be required to populate the Namespaces by querying them using XML Parser and Linq.

The way to allow the deserializer to hydrate all Namespaces including prefixes is to add a property named xmlns of Type XmlSerializerNamespaces to your class and decorate this property with XmlNamespaceDeclarations attribute.

Deserializing the XML with the XmlSerializer.Deserialize() will correctly load a list of all Namespaces with prefixes defined in the XML document.

The XmlSerializerNamespaces contains a Dictionary of XmlQualifiedName named Namespaces that contains a list of Name and Namespace as key value pair. The value of Name for default xmlns is Empty but the Namespace will contain the defined value. If your XML document contains xmlns with prefix, the prefix is loaded into the Name property.

Leave a comment