用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c#代码库

使一个model序列化为xml

2012-10-19 作者: 神马举报

[c#]代码库

//使一个model序列化为xml
//
 
public static class SerializeHelper
{
    #region BinaryFormatter
    #region SerializeObject
    public static byte[] SerializeObject ( object obj ) //obj 可以是数组
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream memoryStream = new MemoryStream();//此种情况下,mem_stream的缓冲区大小是可变的
        formatter.Serialize ( memoryStream, obj );
        byte[] buff = memoryStream.ToArray();
        memoryStream.Close();
        return buff;
    }
    public static void SerializeObject ( object obj, ref byte[] buff, int offset ) //obj 可以是数组
    {
        byte[] rude_buff = SerializeHelper.SerializeObject ( obj );
        for ( int i = 0; i < rude_buff.Length; i++ )
        {
            buff[offset + i] = rude_buff[i];
        }
    }
    #endregion
    #region DeserializeBytes
    public static object DeserializeBytes ( byte[] buff, int index, int count )
    {
        IFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream ( buff, index, count );
        object obj = formatter.Deserialize ( stream );
        stream.Close();
        return obj;
    }
    #endregion
    #endregion
    #region SoapFormatter
    #region SerializeObjectToString
    ///
    /// SerializeObjectToString 将对象序列化为SOAP XML 格式。
    /// 如果要将对象转化为简洁的xml格式,请使用ESBasic.Persistence.SimpleXmlConverter类。
    ///
    public static string SerializeObjectToString ( object obj )
    {
        IFormatter formatter = new SoapFormatter();
        MemoryStream stream = new MemoryStream();
        formatter.Serialize ( stream, obj );
        stream.Position = 0;
        StreamReader reader = new StreamReader ( stream );
        string res = reader.ReadToEnd();
        stream.Close();
        return res;
    }
    #endregion
    #region DeserializeString
    public static object DeserializeString ( string str,System.Text.Encoding ecnoding )
    {
        byte[] buff = ecnoding.GetBytes ( str );
        IFormatter formatter = new SoapFormatter();
        MemoryStream stream = new MemoryStream ( buff, 0, buff.Length );
        object obj = formatter.Deserialize ( stream );
        stream.Close();
        return obj;
    }
    #endregion
    #endregion
    #region XmlSerializer
    #region XmlObject
    public static string XmlObject ( object obj )
    {
        XmlSerializer xmlSerializer = new XmlSerializer ( obj.GetType() );
        MemoryStream stream = new MemoryStream();
        xmlSerializer.Serialize ( stream, obj );
        stream.Position = 0;
        StreamReader reader = new StreamReader ( stream );
        string res = reader.ReadToEnd();
        stream.Close();
        return res;
    }
    #endregion
    #region ObjectXml
    public static T ObjectXml ( string str, System.Text.Encoding ecnoding )
    {
        return ( T ) SerializeHelper.ObjectXml ( str, typeof ( T ), ecnoding );
    }
    public static object ObjectXml ( string str, Type targetType, System.Text.Encoding ecnoding )
    {
        byte[] buff = ecnoding.GetBytes ( str );
        XmlSerializer xmlSerializer = new XmlSerializer ( targetType );
        MemoryStream stream = new MemoryStream ( buff, 0, buff.Length );
        object obj = xmlSerializer.Deserialize ( stream );
        stream.Close();
        return obj;
    }
    #endregion
    #endregion
    #region SaveToFile
    ///
    /// SaveToFile 将对象的二进制序列化后保存到文件。
    ///
    public static void SaveToFile ( object obj, string filePath )
    {
        FileStream stream = new FileStream ( filePath, FileMode.CreateNew );
        IFormatter formatter = new BinaryFormatter();
        formatter.Serialize ( stream, obj );
        stream.Flush();
        stream.Close();
    }
    #endregion
    #region ReadFromFile
    ///
    /// ReadFromFile 从文件读取二进制反序列化为对象。
    ///
    public static object ReadFromFile ( string filePath )
    {
        byte[] buff = FileHelper.ReadFileReturnBytes ( filePath );
        return SerializeHelper.DeserializeBytes ( buff, 0, buff.Length );
    }
    #endregion
}
///
/// 序列化类
///
public static class Serializer
{
 
    ///
    /// Static Constructor is used to set the CanBinarySerialize value only once for the given security policy
    ///
    static Serializer()
    {
        SecurityPermission sp = new SecurityPermission ( SecurityPermissionFlag.SerializationFormatter );
        try
        {
            sp.Demand();
            CanBinarySerialize = true;
        }
        catch ( SecurityException )
        {
            CanBinarySerialize = false;
        }
    }
    ///
    /// Readonly value indicating if Binary Serialization (using BinaryFormatter) is allowed
    ///
    public static readonly bool CanBinarySerialize;
    ///
    /// Converts a .NET object to a byte array. Before the conversion happens, a check with
    /// Serializer.CanBinarySerialize will be made
    ///
    /// Object to convert
    /// A byte arry representing the object paramter. Null will be return if CanBinarySerialize is false
    public static byte[] ConvertToBytes ( object objectToConvert )
    {
        byte[] byteArray = null;
        if ( CanBinarySerialize )
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            using ( MemoryStream ms = new MemoryStream() )
            {
                binaryFormatter.Serialize ( ms, objectToConvert );
 
                // Set the position of the MemoryStream back to 0
                //
                ms.Position = 0;
                // Read in the byte array
                //
                byteArray = new Byte[ ms.Length ];
                ms.Read ( byteArray, 0, byteArray.Length );
                ms.Close();
            }
        }
        return byteArray;
    }
    ///
    /// Saves an object to disk as a binary file.
    ///
    /// Object to Save
    /// Location of the file
    /// true if the save was succesful.
    public static bool SaveAsBinary ( object objectToSave, string path )
    {
        if ( objectToSave != null && CanBinarySerialize )
        {
            byte[] ba = ConvertToBytes ( objectToSave );
            if ( ba != null )
            {
                using ( FileStream fs = new FileStream ( path, FileMode.OpenOrCreate, FileAccess.Write ) )
                {
                    using ( BinaryWriter bw = new BinaryWriter ( fs ) )
                    {
                        bw.Write ( ba );
                        return true;
                    }
                }
            }
        }
        return false;
    }
 
    ///
    /// Converts a .NET object to a string of XML. The object must be marked as Serializable or an exception
    /// will be thrown.
    ///
    /// Object to convert
    /// A xml string represting the object parameter. The return value will be null of the object is null
    public static string ConvertToString ( object objectToConvert )
    {
        string xml = null;
        if ( objectToConvert != null )
        {
            //we need the type to serialize
            Type t = objectToConvert.GetType();
            XmlSerializer ser = new XmlSerializer ( t );
            //will hold the xml
            using ( StringWriter writer = new StringWriter ( CultureInfo.InvariantCulture ) )
            {
                ser.Serialize ( writer, objectToConvert );
                xml = writer.ToString();
                writer.Close();
            }
        }
        return xml;
    }
    public static void SaveAsXML ( object objectToConvert, string path )
    {
        if ( objectToConvert != null )
        {
            //we need the type to serialize
            Type t = objectToConvert.GetType();
            XmlSerializer ser = new XmlSerializer ( t );
            //will hold the xml
            using ( StreamWriter writer = new StreamWriter ( path ) )
            {
                ser.Serialize ( writer, objectToConvert );
                writer.Close();
            }
        }
    }
 
    ///
    /// Converts a byte array to a .NET object. You will need to cast this object back to its expected type.
    /// If the array is null or empty, it will return null.
    ///
    /// An array of bytes represeting a .NET object
    /// The byte array converted to an object or null if the value of byteArray is null or empty
    public static object ConvertToObject ( byte[] byteArray )
    {
        object convertedObject = null;
        if ( CanBinarySerialize && byteArray != null && byteArray.Length > 0 )
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            using ( MemoryStream ms = new MemoryStream() )
            {
                ms.Write ( byteArray, 0, byteArray.Length );
                // Set the memory stream position to the beginning of the stream
                //
                ms.Position = 0;
                if ( byteArray.Length > 4 )
                    convertedObject = binaryFormatter.Deserialize ( ms );
                ms.Close();
            }
        }
        return convertedObject;
    }
    ///
    /// Converts a string of xml to the supplied object type.
    ///
    /// Xml representing a .NET object
    /// The type of object which the xml represents
    /// A instance of object or null if the value of xml is null or empty
    public static object ConvertToObject ( XmlNode node, Type objectType )
    {
        object convertedObject = null;
        if ( node != null )
        {
            using ( StringReader reader = new StringReader ( node.OuterXml ) )
            {
                XmlSerializer ser = new XmlSerializer ( objectType );
                convertedObject = ser.Deserialize ( reader );
                reader.Close();
            }
        }
        return convertedObject;
    }
 
    public static object ConvertFileToObject ( string path, Type objectType )
    {
        object convertedObject = null;
        if ( path != null && path.Length > 0 )
        {
            using ( FileStream fs = new FileStream ( path, FileMode.Open, FileAccess.Read ) )
            {
                XmlSerializer ser = new XmlSerializer ( objectType );
                convertedObject = ser.Deserialize ( fs );
                fs.Close();
            }
        }
        return convertedObject;
    }
    ///
    /// Converts a string of xml to the supplied object type.
    ///
    /// Xml representing a .NET object
    /// The type of object which the xml represents
    /// A instance of object or null if the value of xml is null or empty
    public static object ConvertToObject ( string xml, Type objectType )
    {
        object convertedObject = null;
        if ( !string.IsNullOrEmpty ( xml ) )
        {
            using ( StringReader reader = new StringReader ( xml ) )
            {
                XmlSerializer ser = new XmlSerializer ( objectType );
                convertedObject = ser.Deserialize ( reader );
                reader.Close();
            }
        }
        return convertedObject;
    }
    public static object LoadBinaryFile ( string path )
    {
        if ( !File.Exists ( path ) )
            return null;
        using ( FileStream fs = new FileStream ( path, FileMode.Open, FileAccess.Read ) )
        {
            BinaryReader br = new BinaryReader ( fs );
            byte[] ba = new byte[ fs.Length ];
            br.Read ( ba, 0, ( int ) fs.Length );
            return ConvertToObject ( ba );
        }
    }
    ///
    /// Creates a NameValueCollection from two string. The first contains the key pattern and the second contains the values
    /// spaced according to the kys
    ///
    /// Keys for the namevalue collection
    /// Values for the namevalue collection
    /// A NVC populated based on the keys and vaules
    ///
    /// string keys = "key1:S:0:3:key2:S:3:2:";
    /// string values = "12345";
    /// This would result in a NameValueCollection with two keys (Key1 and Key2) with the values 123 and 45
    ///
    public static NameValueCollection ConvertToNameValueCollection ( string keys, string values )
    {
        NameValueCollection nvc = new NameValueCollection();
        if ( keys != null && values != null && keys.Length > 0 && values.Length > 0 )
        {
            char[] splitter = new char[ 1 ] { ':' };
            string[] keyNames = keys.Split ( splitter );
            for ( int i = 0; i < ( keyNames.Length / 4 ); i++ )
            {
                int start = int.Parse ( keyNames[ ( i * 4 ) + 2 ], CultureInfo.InvariantCulture );
                int len = int.Parse ( keyNames[ ( i * 4 ) + 3 ], CultureInfo.InvariantCulture );
                string key = keyNames[ i * 4 ];
                //Future version will support more complex types
                if ( ( ( keyNames[ ( i * 4 ) + 1 ] == "S" ) && ( start >= 0 ) ) && ( len > 0 ) && ( values.Length >= ( start + len ) ) )
                {
                    nvc[ key ] = values.Substring ( start, len );
                }
            }
        }
        return nvc;
    }
    ///
    /// Creates a the keys and values strings for the simple serialization based on a NameValueCollection
    ///
    /// NameValueCollection to convert
    /// the ref string will contain the keys based on the key format
    /// the ref string will contain all the values of the namevaluecollection
    public static void ConvertFromNameValueCollection ( NameValueCollection nvc, ref string keys, ref string values )
    {
        if ( nvc == null || nvc.Count == 0 )
            return;
        StringBuilder sbKey = new StringBuilder();
        StringBuilder sbValue = new StringBuilder();
        int index = 0;
        foreach ( string key in nvc.AllKeys )
        {
            if ( key.IndexOf ( ':' ) != -1 )
                throw new ArgumentException ( "ExtendedAttributes Key can not contain the character \":\"" );
            string v = nvc[ key ];
            if ( !string.IsNullOrEmpty ( v ) )
            {
                sbKey.AppendFormat ( "{0}:S:{1}:{2}:", key, index, v.Length );
                sbValue.Append ( v );
                index += v.Length;
            }
        }
        keys = sbKey.ToString();
        values = sbValue.ToString();
    }
}


网友评论    (发表评论)

共1 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...