Search code examples
c#.netxmlserializationxml-serialization

How to NOT have a wrapper element for list elements after XML serialization


I have a class Payment. The class structure looks like this:

public class Payment
{
  public decimal Amount{get;set;}
  public List<Loan> Loans{get;set;}
}
public class Loan
{
  public decimal Debt{get;set;}
  public string Lender{get;set;}
}

when I serialize this to XML, by default it will produce something like this:

<Payment>
  <Amount>...</Amount>
  <Loans>
    <Loan>...</Loan>
    <Loan>...</Loan>
  </Loans>
</Payment>

But I want an output like this:

<Payment>
  <Amount>...</Amount>
  <Loan>...</Loan>
  <Loan>...</Loan>
</Payment>

How can I achieve my desired output?

My XML serialization code is this:

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Payment));

StringBuilder sb = new StringBuilder();
using (System.IO.TextWriter writer = new System.IO.StringWriter(sb))
{                    
  serializer.Serialize(writer, mainDocument);
  writer.Flush();
}
finalXML = sb.ToString();
// finalXML contains the XML string

Solution

  • Just define your Loans as a XmlElement:

    public class Payment
    {
        public decimal Amount { get; set; }
        [XmlElement("Loan")] 
        public List<Loan> Loans { get; set; }
    }
    public class Loan
    {
        public decimal Debt { get; set; }
        public string Lender { get; set; }
    }