Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML attribute with namespace other than its parent's is deserialized as null

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?

like image 607
Sushi271 Avatar asked Jan 30 '26 16:01

Sushi271


1 Answers

You are applying your namespace "http://sub.com" element Child, not to its value attribute. In your XML, you specifically apply "http://main.com" to both, Parent and Child. You can fix your namespaces like this:

[XmlRoot(ElementName = "Parent", Namespace = "http://main.com")]
public class Parent
{
    [XmlElement(ElementName = "Child")]
    public Child Child{ get; set; }
}

[XmlType(Namespace = "http://main.com")]
public class Child
{
    [XmlAttribute(AttributeName = "value", Namespace = "http://sub.com")]
    public string Value { get; set; }
}
like image 63
Sefe Avatar answered Feb 02 '26 04:02

Sefe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!