Search code examples
c#xmlserializer

Writing to SML XmlSerializer c#


I found this sample code on MSDN but the problem with the code is that it writes all the XML in a single line. I want indentation and line breaks. I don't know how to insert XmlWriterSettings in the code.

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

// This is the class that will be serialized. 
public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
   public decimal LineTotal;
   // A custom method used to calculate price per item. 
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test{
   public static void Main()
   {
      Test t = new Test();
      // Write a purchase order.
      t.SerializeObject("simple.xml");
   }

   private void SerializeObject(string filename)
   {
      Console.WriteLine("Writing With XmlTextWriter");

      XmlSerializer serializer = 
      new XmlSerializer(typeof(OrderedItem));
      OrderedItem i = new OrderedItem();
      i.ItemName = "Widget";
      i.Description = "Regular Widget";
      i.Quantity = 10;
      i.UnitPrice = (decimal) 2.30;
      i.Calculate();
      // Create an XmlTextWriter using a FileStream.
      Stream fs = new FileStream(filename, FileMode.Create);
      XmlWriter writer = 
      new XmlTextWriter(fs, Encoding.Unicode);
      // Serialize using the XmlTextWriter.
      serializer.Serialize(writer, i);
      writer.Close();
   }
}

Solution

  • You need to set the appropriate properties in your XmlWriterSettings class before the call to XmlWriter.Create().

    Also, I'd suggest the following additional changes:

    1. Stream and XmlWriter are both disposable, thus should be wrapped in a using statement, in case an exception gets thrown while writing the file.

    2. For clarity, separate out a generic method to serialize any object from the code to calculate and write your OrderedItem class.

    Thus:

        private void SerializeObject(string filename)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem));
            OrderedItem i = new OrderedItem();
            i.ItemName = "Widget";
            i.Description = "Regular Widget";
            i.Quantity = 10;
            i.UnitPrice = (decimal)2.30;
            i.Calculate();
    
            Console.WriteLine(string.Format("Writing \"{0}\" With XmlTextWriter", filename));
            SerializeObject(i, filename);
        }
    
        public static void SerializeObject<T>(T obj, string filename)
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            using (var fs = new FileStream(filename, FileMode.Create))
            {
                var settings = new XmlWriterSettings() { Indent = true, IndentChars = "    ", Encoding = Encoding.Unicode };
                using (var writer = XmlWriter.Create(fs, settings))
                {
                    serializer.Serialize(writer, obj);
                }
            }
        }