在ASP.NET MVC中从API反序列化XML

时间:2014-09-04 19:17:30

标签: c# asp.net xml xml-deserialization

我正在构建一个asp.net MVC程序,它将使用httpclient使用基于xml的API,并使用XmlSerializer将其反序列化为对象。
但是出现了错误:XML文档中存在错误(1,2)。
内部例外:{" http://schemas.datacontract.org/2004/07/Service.Models'>没想到。"} 我的怀疑在某种程度上让我搞砸了模特课,但我不确定。 谢谢!

来自API的

XML:

<ArrayDTO xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/RestService.Models">
  <LaborDTO>
    <CreateDate>2014-04-09T09:20:15.57</CreateDate>
    <CreateUser>test</CreateUser>
  </LaborDTO>
  <LaborDTO>
    <CreateDate>2014-04-09T09:20:15.57</CreateDate>
    <CreateUser>test</CreateUser>
  </LaborDTO>
</ArrayDTO>

以下是我的C#代码:

HttpClient client = new HttpClient();
....
HttpResponseMessage response = client.GetAsync(serviceString).Result;
....
XmlSerializer ds = new XmlSerializer(typeof(ArrayDTO));
var obj = ds.Deserialize(response.Content.ReadAsStreamAsync().Result);
ArrayDTO data = (ArrayDTO) obj;
foreach (var item in ArrayDTO.collection) {
....
}

这是我的模特课:

public class LaborDTO
{
    public Nullable<System.DateTime> CreateDate { get; set; }
    public string CreateUser { get; set; }
}

public class ArrayDTO
{
    [XmlAttribute("xmlns")]
    public string schema { get; set; }
    [XmlElement("LaborDTO")]
    public LaborDTO[] collection { get; set; }
}

1 个答案:

答案 0 :(得分:3)

您只需要使用Xml命名空间

[XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/RestService.Models")]
public class ArrayDTO
{
    [XmlElement("LaborDTO")]
    public LaborDTO[] collection { get; set; }
}