Feedback

C# - Objekt serialisierung

Veröffentlicht von am 6/28/2010
(1 Bewertungen)
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
  
public class XMLSerializationUtility
{
    public static T DeserializeObject<T>( Encoding encoding, string xml )
    {
        try
        {
            using (MemoryStream memoryStream = new MemoryStream( StringToByteArray( encoding, xml ) ) )
            {
                using ( XmlTextWriter xmlTextWriter = new XmlTextWriter( memoryStream, encoding ) )
                {
                    XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) );
 
                    return (T)xmlSerializer.Deserialize( memoryStream );
                }
            }
        }
        catch
        {
            return default( T );
        }
    }
 
    public static string SerializeObject<T>( Encoding encoding, T obj )
    {
        try
        {
            MemoryStream memoryStream = new MemoryStream();
 
            using ( XmlTextWriter xmlTextWriter = new XmlTextWriter( memoryStream, encoding ) )
            {
                XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) );
                xmlSerializer.Serialize( xmlTextWriter, obj );
 
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            }
 
            return ByteArrayToString( encoding, memoryStream.ToArray() );
        }
        catch
        {
            return string.Empty;
        }
    }
 
    private static Byte[] StringToByteArray( Encoding encoding, string xml )
    {
        return encoding.GetBytes( xml );
    }
 
    private static string ByteArrayToString( Encoding encoding, byte[] byteArray )
    {
        return encoding.GetString( byteArray );
    }
}
Abgelegt unter Objekt serialisierung.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!