I have a xml string without any namespaces that needs to deserialise to an object that has namespace in
XmlType attribute. When I try to deserialise it with XmlSerializer, all my properties are not populated.
[XmlType("SomeClass", AnonymousType = true, Namespace = "http://abc.some.namespace")]
public class SomeClass
{
[XmlElement(Order = 0)]
public string Label { get; set; }
[XmlElement(Order = 1)]
public int Number { get; set; }
}
var xs = new XmlSerializer(typeof(SomeClass));
var xmlToDeserialize = @"<SomeClass><Label>ABC</Label><Number>10</Number></SomeClass>";
SomeClass result = (SomeClass)xs.Deserialize(new StringReader(xmlToDeserialize));

To fix it, I need to add my own
XmlTextReader that will replace it with the namespace from class. I also want to be able to specify node names that I don’t want to namespace replacement which usually the root node.
public class XmlNamespaceReplaceReader : XmlTextReader
{
private readonly string _oldNamespaceUri;
private readonly string _newNamespaceUri;
private readonly string[] _excludeNodeNames;
public XmlNamespaceReplaceReader(TextReader reader, string oldNamespaceUri, string newNamespaceURI, params string[] excludeNodeNames) : base(reader)
{
_oldNamespaceUri = oldNamespaceUri;
_newNamespaceUri = newNamespaceURI;
_excludeNodeNames = excludeNodeNames;
}
public override string NamespaceURI
{
get
{
if (NodeType != XmlNodeType.Attribute &&
base.NamespaceURI == _oldNamespaceUri &&
!_excludeNodeNames.Contains(Name))
{
return _newNamespaceUri;
}
else
{
return base.NamespaceURI;
}
}
}
}
This is how its used
var xs = new XmlSerializer(typeof(SomeClass));
var xmlToDeserialize = @"<SomeClass><Label>ABC</Label><Number>10</Number></SomeClass>";
SomeClass result2 = (SomeClass)xs.Deserialize(new XmlNamespaceReplaceReader(new StringReader(xmlToDeserialize),
string.Empty, "http://abc.some.namespace", "SomeClass"));
