Serialize and Deserialize (2) : Serialization « File Stream « C# / C Sharp






Serialize and Deserialize (2)

        

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

public static class Utils
{
    public static string Serialize(object o)
    {
        string xml;
        XmlSerializer serializer = new XmlSerializer(o.GetType());
        StringBuilder sb = new StringBuilder();
        using (XmlWriter writer = XmlWriter.Create(sb))
        {
            serializer.Serialize(writer, o);
            xml = sb.ToString();
        }
        return xml;
    }

    public static T Deserialize<T>(string xml)
    {
        if (xml == null)
            return default(T);

        T ret;
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        using (StringReader stream = new StringReader(xml))
        {
            ret = (T)serializer.Deserialize(stream);
        }

        return ret;
    }

}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Use Serializable attribute to mark a generic class
2.Use Serializable attribute to mark a class
3.Deserialize Object
4.Serialize and DeSerialize
5.Three types of Serialization: Binary, Soap, XML
6.Use XML Serialization with Custom ObjectsUse XML Serialization with Custom Objects
7.Working with the Serializable Attribute
8.NonSerialized attributesNonSerialized attributes
9.Serialize hiearchy classesSerialize hiearchy classes
10.C# Serialization C# Serialization
11.Serial Employee class
12.Set XML tag name for Serialization
13.illustrates binary serializationillustrates binary serialization
14.Deserialize
15.Collection Serialization
16.Serializes an object to binary
17.Deserializes an object from binary
18.Object to string serialization/Deserialization
19.Object to byte array serialization/Deserialization
20.Javascript Serializer
21.Binary Serializer
22.Deserialize the incomming data to the T datatype, this method used to deserialize the test cases data to the required entity
23.Serialization Utility
24.Serialization Utilities
25.Clone With Serialization