让我直截了当。如果XMLArray元素为null,是否可以不序列化它?如下面的XML“详细信息”一样。如果它为null,是否可以不用XML。请检查我的代码,并会对它有一些想法。
<agr:InvoiceNo>99999</agr:InvoiceNo>
<agr:Header>
<agr:LineNo>1</agr:LineNo>
<agrlib:InvoiceDate>2013-02-13</agrlib:InvoiceDate>
<agrlib:DueDate>2013-03-15</agrlib:DueDate>
<agr:ArchiveRef>27624642</agr:ArchiveRef>
<agr:ArchivePath>Images\20130315\10_00000030_00000</agr:ArchivePath>
<agr:Currency>SEK</agr:Currency>
<agr:Seller>
<agrlib:CompRegNo>999999</agrlib:CompRegNo>
</agr:Seller>
<agr:Buyer>
<agrlib:CompanyCode>10</agrlib:CompanyCode>
<agr:Accountable />
</agr:Buyer>
<agr:PaymentInfo>
<agr:AccountNumber>99999</agr:AccountNumber>
<agrlib:BacsId />
</agr:PaymentInfo>
<agrlib:ReferenceCode>
<agrlib:Code>AA</agrlib:Code>
<agrlib:Value>AAAA</agrlib:Value>
<agrlib:Description />
</agrlib:ReferenceCode>
</agr:Header>
<Details /> <!-- this one -->
<agr:Summary>
<agr:TotalTax>170.36</agr:TotalTax>
<agr:TotalInclTax>1590.00</agr:TotalInclTax>
</agr:Summary>
</agr:Invoice>
[Serializable]
public class Invoice
{
private Header _header = new Header();
private Summary _summary = new Summary();
private List<Detail> _details = new List<Detail>();
[XmlElement("InvoiceNo")]
public string InvoiceNo { get; set; }
[XmlElement("Header")]
public Header Header
{
get { return _header; }
set { _header = value; }
}
[XmlArray("Details"), XmlArrayItem("Detail", typeof(Detail), IsNullable=false)]
public List<Detail> Details
{
get { return _details; }
set { _details = value; }
}
[XmlElement("Summary")]
public Summary Summary
{
get { return _summary; }
set { _summary = value; }
}
}
[XmlType(TypeName = "Detail"), Serializable]
public class Detail
{
private Product _product = new Product();
static CultureInfo ci = CultureInfo.InvariantCulture;
private float _lineTotExclTax = 0;
[XmlElement("LineNo")]
public int LineNo { get; set; }
[XmlIgnore]
public float LineTotExclTax
{
get { return _lineTotExclTax; }
set { _lineTotExclTax = value; }
}
[XmlElement("LineTotExclTax")]
public string CustomLineTotExclTax
{
get { return LineTotExclTax.ToString("#0.00", ci); }
set { float.TryParse(value, NumberStyles.Float, ci, out _lineTotExclTax); }
}
[XmlElement("Products")]
public Product Product
{
get { return _product; }
set { _product = value; }
}
}
答案 0 :(得分:5)
如果列表确实为null
,则 将被忽略。要获得您显示的输出,它必须是一个空的非null
列表,可能是由于字段初始化程序:
private List<Detail> _details = new List<Detail>();
如果您无法null
,请考虑ShouldSerialize*
:
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeDetails()
{
return _details != null && _details.Count != 0;
}
这定义了属性Details
应该/不应该序列化的自定义规则。