Strings the serialize Object to XML. - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Strings the serialize Object to XML.

Demo Code


using System.Xml.Serialization;
using System.IO;/* w w w.  jav a 2s.  c om*/
using System.Xml;
using System.Text.RegularExpressions;
using System;

public class Main{
        /// <summary>
        /// Strings the serialize.   
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns></returns>
        /// <remarks></remarks>
      public static string StringSerialize(object obj)
      {
         XmlSerializer serializer = new XmlSerializer(obj.GetType());
         StringWriter writer1 = new StringWriter();
         serializer.Serialize(writer1, obj);

         StringReader reader = new StringReader(writer1.ToString());
         StringWriter writer2 = new StringWriter();

         // This is because .NET's XML Serialization is a but bunk and puts a dodgy first line in the xml
         reader.ReadLine();
         writer2.WriteLine(@"<?xml version=""1.0""?>");
         writer2.Write(reader.ReadToEnd());

         return writer2.ToString();
      }
}

Related Tutorials