2

我正在尝试反序列化一个看起来像这样的 xml 文档

<invoices>
  <invoice>2848</invoice>
  <invoice>2849</invoice>
  <invoice>2850</invoice>
  <invoice>2851</invoice>
  <invoice>2852</invoice>
</invoices>

进入一个 C# 对象,但我无法让它工作。我正在使用DataContractSerializer

这是我的课的样子:

[DataContract(Name = "invoices", Namespace = "")]
public class Invoices
{
    [DataMember(Name = "invoice")]
    public Invoice[] InvoiceIds { get; set; }
}

[DataContract(Name = "invoice", Namespace = "")]
public class Invoice
{
    [DataMember(Name = "invoice")]
    public string Id { get; set; }
}

当然,这是行不通的。我收到此错误:

{"Error in line 1 position 24. Expecting state 'Element'.. Encountered 'Text'  with name '', namespace ''. "}

我无法控制 Xml。

4

1 回答 1

4

尝试[CollectionDataContract]在这种情况下使用 a:

public class StackOverflow_10705733
{
    [CollectionDataContract(Name = "invoices", ItemName = "invoice", Namespace = "")]
    public class Invoices : List<int>
    {
        [DataMember(Name = "invoice")]
        public int[] InvoiceIds { get; set; }
    }
    public static void Test()
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof(Invoices));
        string xml = @"<invoices>
                          <invoice>2848</invoice>
                          <invoice>2849</invoice>
                          <invoice>2850</invoice>
                          <invoice>2851</invoice>
                          <invoice>2852</invoice>
                        </invoices>";
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
        Invoices value = dcs.ReadObject(ms) as Invoices;
        Console.WriteLine(string.Join(",", value));
    }
}
于 2012-05-22T16:08:53.413 回答