一个序列化与反序列化object的方法

 

        /// <summary>
/// XML序列化对象
/// </summary>
/// <param name="emp">object that would be converted into xml</param>
/// <returns></returns>
public static string ObjectToXML(Object Instance)
{
MemoryStream stream
= null;
TextWriter writer
= null;
string ObjectXml = string.Empty;
try
{
stream
= new MemoryStream(); // read xml in memory
writer = new StreamWriter(stream, Encoding.UTF8);

// get serialise object
Type t = Instance.GetType();
XmlSerializer serializer
= new XmlSerializer(t);

XmlSerializerNamespaces xsn
= new XmlSerializerNamespaces();
xsn.Add(
string.Empty, string.Empty);

serializer.Serialize(writer, Instance, xsn);
// read object
int count = (int)stream.Length; // saves object in memory stream
byte[] arr = new byte[count];
stream.Seek(
0, SeekOrigin.Begin);
// copy stream contents in byte array
stream.Read(arr, 0, count);
//UnicodeEncoding utf = new UnicodeEncoding(); // convert byte array to string
UTF8Encoding utf = new UTF8Encoding();
ObjectXml
= utf.GetString(arr).Trim();
}
catch (Exception ex)
{
string ss = ex.Message;
}
finally
{
if (stream != null && stream.Length > 0)
{
stream.Close();
}
if (writer != null)
{
writer.Close();
}
}

return FormatXml(ObjectXml);
}

/// <summary>
/// 格式化XML
/// </summary>
/// <param name="Xml"></param>
/// <returns></returns>
static string FormatXml(string Xml)
{
if (string.IsNullOrEmpty(Xml))
{
return "";
}

string startXml = "<?";
string endXml = "?>";
int startPos = Xml.IndexOf(startXml);
int endPos = Xml.IndexOf(endXml);
if (!(startPos == -1 || endPos == -1))
{
return Xml.Remove(startPos, endPos - startPos + endXml.Length);
}
else
{
return Xml;
}
}

/// <summary>
/// 反序列化XML字符串
/// </summary>
/// <param name="xml">xml data of employee</param>
/// <returns></returns>
public static object XMLToObject(string xml, Type t)
{
StringReader stream
= null;
XmlTextReader reader
= null;
Object o
= null;
try
{
// serialise to object
XmlSerializer serializer = new XmlSerializer(t);
stream
= new StringReader(xml); // read xml data
reader = new XmlTextReader(stream); // create reader

//XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
//xsn.Add("xmlns", "http://tempuri.org/XMLSchema.xsd");
// covert reader to object
o = serializer.Deserialize(reader);
}
catch (Exception ex)
{
string ss = ex.Message;
}
finally
{
if (stream != null)
{
stream.Close();
}
if (reader != null)
{
reader.Close();
}
}

return o;
}

 

 

posted @ 2008-11-20 11:48  builderman  阅读(776)  评论(0编辑  收藏  举报