无法将xml反序列化为List <t> </t>

时间:2014-01-31 17:27:47

标签: c# xml list xmlserializer

我试图使用XmlSerializer将wcf web服务的xml响应反序列化为List,但它失败并显示异常消息: XML文档中存在错误(1,2)

的xml:

<ArrayOfNote xmlns="http://schemas.datacontract.org/2004/07/NotebookService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Note>
    <Author>Redouane</Author>
    <Body>Test note</Body>
    <CreationDate>2014-01-28T00:00:00</CreationDate>
    <Id>1</Id>
    <Title>Hello World</Title>
  </Note>
</ArrayOfNote>

C#:

public class Note
{
    public int Id { get; set; }
    public string Title { get; set; }
    public System.DateTime CreationDate { get; set; }
    public string Author { get; set; }
    public string Body { get; set; }
}

这是我编写的用于反序列化收到的流的代码

private HttpClient client = new HttpClient();
private List<Note> notes = new List<Note>();

。 。

XmlSerializer serializer = new XmlSerializer(typeof(List<Note>));
var responseData = await response.Content.ReadAsStreamAsync();
List<Note> list = serializer.Deserialize(responseData) as List<Note>;

请帮忙!

1 个答案:

答案 0 :(得分:2)

按如下方式更改序列化程序的创建,它应该可以正常工作。

XmlSerializer serializer = new XmlSerializer(typeof(List<Note>), 
                                new XmlRootAttribute("ArrayOfNote") { 
                                    Namespace = "http://schemas.datacontract.org/2004/07/NotebookService" 
                                });