XmlSerializer在序列化时删除数据

时间:2016-11-02 10:03:48

标签: c# xml-serialization

序列化大型 XML对象时,我遇到了一个非常烦人的问题。我已经定义了一个类 FetchYearlyInvoiceStatusRequest

[Serializable]
public class FetchYearlyInvoiceStatusRequest
{
    [XmlArray("INVOICES")]
    [XmlArrayItem("INVOICE", typeof(InvoiceRequest))]
    public List<InvoiceRequest> Invoices;

}
[Serializable]
public class InvoiceRequest
{
    [XmlElement("CONTRACTACCOUNT")]
    public string ContractAccount;
    [XmlElement("INVOICENUMBER")]
    public string InvoiceNumber;
}

我有一个这个类的实例,列表中有大约700个项目。当我使用此代码将其序列化为XML时:

    XmlSerializer serializerRequest = new XmlSerializer(typeof(FetchYearlyInvoiceStatusRequest));
    string invoices;
    using (var sw = new StringWriter())
    {
        serializerRequest.Serialize(sw, odsrequest);
        invoices = sw.ToString();
    }

发票字符串现在包含一长串发票,但序列化程序(或内存流?)只是切断了中间的一半。所以实际上在输出字符串的中间,文字文本是:

<INVOICE>
  <CONTRACTACCOUNT>3006698362</CONTRACTACCOUNT>
  <INVOICENUMBER>40523461958</INVOICENUMBER>
</INVOICE>
<INVOICE>
  <CONTRACTACCOUNT>3006362096</CONTRACTACCOUNT>
  <INVOICENUMBER>40028149026</INVOICENUMBE...      <CONTRACTACCOUNT>3006362096</CONTRACTACCOUNT>
  <INVOICENUMBER>55002448279</INVOICENUMBER>
</INVOICE>
<INVOICE>
  <CONTRACTACCOUNT>3006362096</CONTRACTACCOUNT>
  <INVOICENUMBER>42514938204</INVOICENUMBER>
</INVOICE>

这只是腐败。当我使用几乎相同的代码写入文件时(但使用StreamWriter而不是StringWriter):

    XmlSerializer serializerRequest = new XmlSerializer(typeof(FetchYearlyInvoiceStatusRequest));
    string invoices;
    using (var sw = new StreamWriter("c:\\temp\\output.xml"))
    {
        serializerRequest.Serialize(sw, odsrequest);
    }

文件中的输出是完美的(在上面切断的位置与上面相同的片段):

<INVOICE>
  <CONTRACTACCOUNT>3006362096</CONTRACTACCOUNT>
  <INVOICENUMBER>40028149026</INVOICENUMBER>
</INVOICE>
<INVOICE>
  <CONTRACTACCOUNT>3007728722</CONTRACTACCOUNT>
  <INVOICENUMBER>40027928855</INVOICENUMBER>
</INVOICE>

请有人告诉我发生了什么。我用谷歌搜索“字符串限制”,“xmlserializer限制等等。没有:(

任何帮助表示赞赏!

0 个答案:

没有答案