I'm trying to deserialize following XML:
<nsMain:Parent xmlns:nsMain="http://main.com">
<nsMain:Child xmlns:nsSub="http://sub.com" nsSub:value="foobar" />
</nsMain:Parent>
Notice the namespace of the attribute is different than namespaces of both elements.
I have two classes:
[XmlRoot(ElementName = "Parent", Namespace = "http://main.com")]
public class Parent
{
[XmlElement(ElementName = "Child")]
public Child Child{ get; set; }
}
[XmlType(Namespace = "http://sub.com")]
public class Child
{
[XmlAttribute(AttributeName = "value")]
public string Value { get; set; }
}
The XML comes as a HTTP POST request's body, inside HttpRequestMessage object. The function for deserializing is:
private Parent ExtractModel(HttpRequestMessage request)
{
var serializer = new XmlSerializer(typeof(Parent));
var model = (Parent)serializer.Deserialize(request.Content.ReadAsStreamAsync().Result);
return model;
}
However, after calling this function it appears that model.Child.Value == null
.
I tried to experiment a bit with the Namespace parameter of C# attributes on classes and properties (e.g. move it to [XmlAttribute], or put both in [XmlType] and [XmlAttribute]), but it didn't change anything. I can't seem to make this right. If I don't use namespace at all (both in request and in the model definition) then the value reads just fine.
What am I missing?