Serialize and deserialize objects as Xml using generic types in C# 2.0

前端之家收集整理的这篇文章主要介绍了Serialize and deserialize objects as Xml using generic types in C# 2.0前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Xml;
usingSystem.IO;
usingSystem.Xml.Serialization;

///<summary>
///
To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
///
</summary>
///
<param name="characters">Unicode Byte Array to be converted to String
</param>
///
<returns>String converted from Unicode Byte Array
</returns>
privatestaticstringUTF8ByteArrayToString(byte[] characters)
{
UTF8Encodingencoding =newUTF8Encoding();
stringconstructedString = encoding.GetString(characters);
return(constructedString);
}

///<summary>
///
Converts the String to UTF8 Byte array and is used in De serialization
///
</summary>
///
<param name="pXmlString"></param>
///
<returns></returns>
privatestaticByte[] StringToUTF8ByteArray(stringpXmlString)
{
UTF8Encodingencoding =newUTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlString);
returnbyteArray;
}

/// <summary>
///
Serialize an object into an XML string
///
</summary>
///
<typeparam name="T"></typeparam>
///
<param name="obj"></param>
///
<returns></returns>
publicstaticstringSerializeObject<T>(T obj)
{
try
{
stringxmlString =null;
MemoryStreammemoryStream =newMemoryStream();
XmlSerializerxs =newXmlSerializer(typeof(T));
XmlTextWriterxmlTextWriter =newXmlTextWriter(memoryStream,Encoding.UTF8);
xs.Serialize(xmlTextWriter,obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlString = UTF8ByteArrayToString(memoryStream.ToArray()); returnxmlString;
}
catch
{
returnstring.Empty;
}
}

///<summary>
///
Reconstruct an object from an XML string
///
</summary>
///
<param name="xml"></param>
///
<returns></returns>
publicstaticT DeserializeObject<T>(stringxml)
{
XmlSerializerxs =newXmlSerializer(typeof(T));
MemoryStreammemoryStream =newMemoryStream(StringToUTF8ByteArray(xml));
XmlTextWriterxmlTextWriter =newXmlTextWriter(memoryStream,Encoding.UTF8);
return(T)xs.Deserialize(memoryStream);
}

Posted on Friday,July 20,2007 8:35 AM |Back to top

猜你在找的XML相关文章