如何使用根而不是同一类型的多个子元素反序列化 Xml

本文关键字:元素 Xml 反序列化 类型 何使用 | 更新日期: 2023-09-27 18:35:03

我正在尝试反序列化如下所示的 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。

如何使用根而不是同一类型的多个子元素反序列化 Xml

尝试对以下方案使用 [CollectionDataContract]

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));
    }
}
相关文章: