Xml Serialization Helper 2 : Xml Serialization « XML « C# / C Sharp






Xml Serialization Helper 2

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

namespace A4G.Utils.Xml
{
  public static class XmlSerializationHelper<T>
  {
    private static readonly XmlSerializer _serializer = new XmlSerializer(typeof(T));

    public static void SerializeToFile(string fileName, T objectToSerialize)
    {
      XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.Default);
      writer.Formatting = Formatting.Indented;

      try
      {
        _serializer.Serialize(writer, objectToSerialize);
      }
      finally
      {
        writer.Close();
      }
    }

    public static T DeserializeFromFile(string fileName)
    {
      XmlTextReader reader = new XmlTextReader(fileName);

      try
      {
        T serializedObject = (T) _serializer.Deserialize(reader);
        return serializedObject;
      }
      finally
      {
        reader.Close();
      }
    }

    public static void SerializeToStream(Stream destination, T objectToSerialize)
    {
      _serializer.Serialize(destination, objectToSerialize);
    }

    public static T DeserializeFromStream(Stream source)
    {
      return (T)_serializer.Deserialize(source);
    }
  }
}

   
    
  








Related examples in the same category

1.Serialize List of Objects
2.Use XmlSerializer
3.Set Xml Attribute when serilzation
4.Use XML Serialization with Custom Objects
5.XmlRootAttribute
6.Takes an XML file and exports the Object it holds
7.Converts an XML string to an object
8.Deserializes/Serializes an xml document back into an object
9.Deserialize with XmlSerializer
10.XmlSerializer Util
11.Serilize to Xml
12.Xml Serialization Helper
13.Tiny Xml Serializer
14.Xml Serialization Manager