Search code examples
c#asp.netxmlserializer

How to use XmlSerializer to remove the level Orders when outputting Customer->Orders->Order


I am looking for a suggestion to resolve the following issue: I have a requirement to remove a level out of XML when serializing the output. (remove the "Orders" level) I am using ASP.NET 4.6 & C#. (not by choice)

here is the Desired Output

<?xml version="1.0"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Fred Flinstone</Name>
    <Order>
      <Description>Cookies</Description>
    </Order>
    <Order>
      <Description>Ice Cream</Description>
    </Order>
</Customer>

here is the current output

<?xml version="1.0"?>
<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Fred Flinstone</Name>
  <Orders>
    <Order>
      <Description>Cookies</Description>
    </Order>
    <Order>
      <Description>Ice Cream</Description>
    </Order>
  </Orders>
</Customer>

Here is the code I used

using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

public static class Test
{
    static void Main()
    {
        string fileName = "dataStuff.txt";
        Test.SerializeItem(fileName); 
    }

    public static void SerializeItem(string fileName)
    {
        var c = new Customer();
        c.Name = "Fred Flinstone";
        c.Orders = new List<Order>();

        var order = new Order();
        order.Description = "Cookies";
        c.Orders.Add(order);

        order = new Order();
        order.Description = "Ice Cream";
        c.Orders.Add(order);

        FileStream s = new FileStream(fileName, FileMode.Create);
        XmlSerializer oSerialiser = new XmlSerializer(typeof(Customer));
        oSerialiser.Serialize(s, c);
        s.Close();
    }
}

public class Customer
{
    public string Name { get; set; }
    public List<Order> Orders{ get; set; }
}

public class Order
{
    public string Description { get; set;  }
}

Thank You for your suggestions.

Why must I add a bunch of gibberish to submit? I want to be succinct/concise.


Solution

  • Mark the List<Order> Orders with XmlElement("Order") attribute.

    public class Customer
    {
        public string Name { get; set; }
    
        [XmlElement("Order")]
        public List<Order> Orders{ get; set; }
    }
    

    Update: You should wrap disposable objects in using statement.

    using (var s = new FileStream(@"C:\temp\m.xml", FileMode.Create))
    {
        var oSerialiser = new XmlSerializer(typeof(Customer));
        oSerialiser.Serialize(s, c);
    }