具有除其父级之外的命名空间的XML属性被反序列化为null

问题描述 投票:1回答:1

我正在尝试反序列化以下XML:

<nsMain:Parent xmlns:nsMain="http://main.com">
    <nsMain:Child xmlns:nsSub="http://sub.com" nsSub:value="foobar" />
</nsMain:Parent>

请注意,属性的名称空间与两个元素的名称空间不同。

我有两节课:

[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; }
}

XML在HttpRequestMessage对象中作为HTTP POST请求的主体出现。反序列化的功能是:

private Parent ExtractModel(HttpRequestMessage request)
{
    var serializer = new XmlSerializer(typeof(Parent));
    var model = (Parent)serializer.Deserialize(request.Content.ReadAsStreamAsync().Result);
    return model;
}

但是,在调用此函数后,它似乎是model.Child.Value == null

我尝试在类和属性上使用C#属性的Namespace参数进行实验(例如将其移动到[XmlAttribute],或者将它们放在[XmlType]和[XmlAttribute]中),但它没有改变任何东西。我似乎无法做到这一点。如果我根本不使用命名空间(在请求和模型定义中),那么值读取就好了。

我错过了什么?

c# xml serialization xml-namespaces xml-deserialization
1个回答
1
投票

您正在应用命名空间"http://sub.com"元素Child,而不是它的value属性。在您的XML中,您特别将"http://main.com"应用于ParentChild。您可以像这样修复名称空间:

[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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.