C#XML可序列化集合

本文关键字:集合 序列化 C#XML | 更新日期: 2023-09-27 18:29:04

我得到了下面的XML(它只是一个大XML的一部分,我有问题),我正试图使Serializable类读取相同的内容。

<BANKTRANLIST>
  <DTSTART>20051001</DTSTART>
  <DTEND>20051028</DTEND>
  <STMTTRN> <!-- This element can repeat any number of times -->
    <TRNTYPE>CHECK</TRNTYPE>
    <DTPOSTED>20051004</DTPOSTED>
    <TRNAMT>-200.00</TRNAMT>
  </STMTTRN>
  <STMTTRN>
    <TRNTYPE>ATM</TRNTYPE>
    <DTPOSTED>20051020</DTPOSTED>
    <TRNAMT>-300.00</TRNAMT>
  </STMTTRN>
</BANKTRANLIST>

我的C#实现

[Serializable]
[XmlRoot("BANKTRANLIST", Namespace = "http://bank.net", IsNullable = false)]
public class BankTransactionList
{
    public BankTransactionList()
    {
        this.StatementTransactions = new List<StatementTransaction>();
    }
    [XmlElement("DTSTART")]
    public string StartDate { get; set; }
    [XmlElement("DTEND")]
    public string EndDate { get; set; }
    [XmlArray("STMTTRN")]
    [XmlArrayItem("STMTTRN")]
    public List<StatementTransaction> StatementTransactions { get; set; }
}

[Serializable]
[XmlRoot("STMTTRN", Namespace = "http://bank.net", IsNullable = false)]
public class StatementTransaction
{
    // TransactionType : ENUM
    [XmlElement("TRNTYPE")]
    public TransactionType TransactionType { get; set; }
    [XmlElement("DTPOSTED")]
    public string DatePosted { get; set; }
    [XmlElement("TRNAMT")]
    public double TransactionAmount { get; set; }
}

我的问题是元素被再次包裹在元素中,结果得到以下输出

...
    <STMTTRN> <!-- This does not match my Original XML -->
      <STMTTRN>
        <TRNTYPE>CHECK</TRNTYPE>
        <DTPOSTED>20051004</DTPOSTED>
        <TRNAMT>-200.00</TRNAMT>
      </STMTTRN>
      <STMTTRN>
        <TRNTYPE>ATM</TRNTYPE>
        <DTPOSTED>20051020</DTPOSTED>
        <TRNAMT>-300.00</TRNAMT>
      </STMTTRN>
    </STMTTRN>

注意:从List属性中删除[XmlArray("STMTTRN")]标记不会解决此问题,而是

如果有人能纠正我或给我一个更好的解决方案,那就太好了!!

C#XML可序列化集合

如果您希望每个项目都有一个元素而没有包装元素,则应为[XmlElement]

[XmlElement("STMTTRN")]
public List<StatementTransaction> StatementTransactions { get; set; }

我想补充一点,为了序列化集合,你需要有这样的东西:

[Serializable]
[XmlRoot("BANKTRANLIST", Namespace = "http://bank.net", IsNullable = false)]
public class BankTransactionList
{
    public BankTransactionList()
    {
        StatementTransactions = new List<StatementTransaction>()
        {
            new StatementTransaction()
        };
    }
    [XmlElement("DTSTART")]
    public string StartDate { get; set; }
    [XmlElement("DTEND")]
    public string EndDate { get; set; }
    [XmlElement("STMTTRN")]
    public List<StatementTransaction> StatementTransactions { get; set; }
}

否则,如果不初始化StatementTransaction对象,列表将不会序列化。