【发布时间】:2017-12-18 14:28:15
【问题描述】:
我正在尝试反序列化以下 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 作为 HTTP POST 请求的正文出现在 HttpRequestMessage 对象中。反序列化的函数是:
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