C# XML Serializable Collection

Randi Ratnayake picture Randi Ratnayake · Mar 26, 2012 · Viewed 8.1k times · Source

I got the below XML (It is just a part of a big XML where I have my problem) that I am trying to make a Serializable class to read the same.

<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>

My C# Implementation

[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; }
}

My problem is element wrapped again in element which results to get the below output

...
    <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>

Note: Removing [XmlArray("STMTTRN")] tag from List property will not resolve this, instead it will be

If any one can correct me or give me a better solution would be great !!

Answer

Marc Gravell picture Marc Gravell · Mar 26, 2012

Should be [XmlElement] if you want an element per item without a wrapper element:

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