我正在尝试反序列化以下XML:
[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; }
}
请注意,属性的名称空间与两个元素的名称空间不同。
我有两个班级:
private Parent ExtractModel(HttpRequestMessage request)
{
var serializer = new XmlSerializer(typeof(Parent));
var model = (Parent)serializer.Deserialize(request.Content.ReadAsStreamAsync().Result);
return model;
}
XML作为HTTP POST请求的主体,在HttpRequestMessage对象中。反序列化的功能是:
model.Child.Value == null
但是,在调用此函数后,它显示为var input = document.getElementById("files");
input.addEventListener("change", function (e) {
file = e.target.files[0],
reader = new FileReader();
reader.onload = function () {
readPdf(reader.result);
}
reader.readAsArrayBuffer(file);
});
function readPdf(buffer) {
PDFJS.disableWorker = true;
PDFJS.getDocument(buffer).then(function (pdf) {
。
我尝试在类和属性上使用C#属性的Namespace参数进行实验(例如将其移动到[XmlAttribute],或者将它们放在[XmlType]和[XmlAttribute]中),但它没有改变任何东西。我似乎无法做到这一点。如果我根本不使用命名空间(在请求和模型定义中),那么值读取就好了。
我错过了什么?
答案 0 :(得分:1)
您正在应用名称空间"http://sub.com"
元素 Child
,而不是其value
属性。在您的XML中,您明确将"http://main.com"
应用于Parent
和Child
。您可以像这样修复名称空间:
[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; }
}