从XML中获取C#对象的通用列表工作正常,除非我将它放在对象列表中

时间:2015-06-10 07:39:25

标签: c# xml xml-deserialization generic-list

这是有效的:(每个Invoice都有很多LineItems)

public class Invoice
{
    public int InvoiceId { get; set; }

    public List<LineItem> LineItems { get; set; }
}

public class LineItem
{
    public int LineItemId { get; set; }
}
string strInvoice = "<Invoice>   <InvoiceId>12345</InvoiceId>   <LineItems>      <LineItem>         <LineItemId>123</LineItemId>      </LineItem>      <LineItem>         <LineItemId>456</LineItemId>      </LineItem>   </LineItems></Invoice>";

object result = new System.Xml.Serialization.XmlSerializer(typeof(Invoice)).Deserialize(new System.IO.StringReader(strInvoice));

对象被完美地反序列化。

但是现在,我尝试制作一份发票清单(我现在将当前的XML字符串括在<Invoices></Invoices>中):

public class InvoiceList
{
    public List<Invoice> Invoices { get; set; }
}

string strInvoices = "<Invoices><Invoice>   <InvoiceId>12345</InvoiceId>   <LineItems>      <LineItem>         <LineItemId>123</LineItemId>      </LineItem>      <LineItem>         <LineItemId>456</LineItemId>      </LineItem>   </LineItems></Invoice></Invoices>";

object results = new System.Xml.Serialization.XmlSerializer(typeof(Invoice)).Deserialize(new System.IO.StringReader(strInvoices));

导致:

There is an error in XML document (1, 2).
{"<Invoices xmlns=''> was not expected."}

如何构建我的类或SQL以反序列化发票列表?

尝试这个 - 这是从被标记为重复的Twitter问题的答案中获取的,我没有得到任何结果:

   string strInvoices = "<Invoices><Invoice>   <InvoiceId>12345</InvoiceId>   <LineItems>      <LineItem>         <LineItemId>123</LineItemId>      </LineItem>      <LineItem>         <LineItemId>456</LineItemId>      </LineItem>   </LineItems></Invoice></Invoices>";
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "Invoices";
    xRoot.IsNullable = true;
    object results = new System.Xml.Serialization.XmlSerializer(typeof(Invoice),xRoot).Deserialize(new System.IO.StringReader(strInvoices));

如果我这样做,我会得到同样的错误:

object results = new System.Xml.Serialization.XmlSerializer(typeof(Invoice),xRoot).Deserialize(new System.IO.StringReader(strInvoices));

如果我按照建议的评论执行此操作,则不会返回任何内容:

 object results = new System.Xml.Serialization.XmlSerializer(typeof(InvoiceList),xRoot).Deserialize(new System.IO.StringReader(strInvoices));

因此与标记为重复的示例不同 我已经花了很多精力来复制这个错误,并使其成为通用的,易于阅读,并尽可能地复制并粘贴到Visual Studio中

1 个答案:

答案 0 :(得分:2)

您反序列化为错误的类型 - 您希望反序列化为InvoiceList

您还应该向InvoiceList类添加一些属性以正确映射元素名称:

[XmlRoot("Invoices")]
public class InvoiceList
{
    [XmlElement("Invoice")]
    public List<Invoice> Invoices { get; set; }
}

然后你应该能够像这样反序列化:

var serializer = new XmlSerializer(typeof(InvoiceList));

using (var reader = new StringReader(strInvoices))
{
    var list = (InvoiceList)serializer.Deserialize(reader);
}

有关工作示例,请参阅https://dotnetfiddle.net/mBtPSP