1

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
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
ITExpert
  • 323
  • 1
  • 2
  • 8

1 Answers1

4

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; }
}
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49