XmlSerializing inherited generic list



[XmlRoot(ElementName="Charges")]
public class Charges : List
{
   private Charge _total;

   public Charges()
   { }

   [XmlElement(ElementName="Total")]
   public Charge Total
   {
      get
      {
         return ((_total == null) new Charge() : _total);
       }
      set
      {
         _total = ((value == null) new Charge() : value);
      }
   }
 }

 


The above code serializes  to

< xml version="1.0" encoding="utf-16" >
<Charges>
  <Charge>
    <Description>Some fancy charge</Description>
    <Detail>Charge for being too fancy</Detail>
    <Amount>82.44</Amount>
  </Charge>
  <Charge>
    <Description>Some fancy charge</Description>
    <Detail>Charge for being too fancy</Detail>
    <Amount>82.44</Amount>
  </Charge>
</Charges>

How can I get Total to show up as:
<Total>
    <Description>Total charge</Description>
    <Detail>Total for all account charges</Detail>
    <Amount>82.44</Amount>
</Total>

I need it to be inside the Charges element though. Any ideas


Answer this question

XmlSerializing inherited generic list

  • Gil Fefer

    The solution is to rename the list elements at the place where the list is exposed as a property, as follows:

    public class Charges {
        List<Charge> list = new List<Charge>();
        public Charges() { }

        [
    XmlElement("Total")]
        public List<Charge> List {
            get { return this.list; }
            set { this.list = value; }
        }
    }

    public class Charge {
        public string Description;
        public string Detail;
        public decimal Amount;
        public Charge() { }
        public Charge(string description,
                            string detail,
                            decimal amount) {
            this.Description = description;
            this.Detail = detail;
            this.Amount = amount;
        }
    }

    Then the following works as you have requested:

    Charges c = new Charges();
    c.List.Add(
    new Charge("Some fancy charge",
                                   
    "Charge for being too fancy", 82.44m));
    c.List.Add(
    new Charge("More charges",
                                   
    "For nothing in particular", 55.27m));

    XmlSerializer s = new XmlSerializer(typeof(Charges));
    s.Serialize(
    Console.Out, c);

    This produces:

    <Charges>
      <
    Total>
        <
    Description>Some fancy charge</Description>
        <
    Detail>Charge for being too fancy</Detail>
        <
    Amount>82.44</Amount>
      </
    Total>
      <
    Total>
        <
    Description>More charges</Description>
        <
    Detail>For nothing in particular</Detail>
        <
    Amount>55.27</Amount>
      </
    Total>
    </
    Charges>

    Enjoy!


  • XmlSerializing inherited generic list