日期:2014-05-20  浏览次数:20977 次

怎么序列化类成字符串并返回
public   static   void   SerializeObject(object   doc,string   strFullPath)
{
XmlSerializer   serializer   =   new   XmlSerializer(doc.GetType());
Stream   fs   =   new   FileStream(strFullPath,   FileMode.Create);
XmlWriter   writer   =   new   XmlTextWriter(fs,   new   UTF8Encoding());
serializer.Serialize(writer,doc);
writer.Close();
fs.Close();
}
以上方法是将一个类序例化成一个文件,我想把它改成序列化成一个字符串并返回,
怎么实现啊?
public   static   string   SerializeObject(object   doc,string   strFullPath)
{
......
}

------解决方案--------------------
/// <summary>
/// 序列化成字符串
/// </summary>
/// <returns> 序列化后的字符串 </returns>
public static string Serialiaze(object obj)
{
XmlSerializer xs = new XmlSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
xs.Serialize(xtw, obj);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string str = sr.ReadToEnd();
xtw.Close();
sr.Close();
ms.Close();
return str;
}
/// <summary>
/// 反序列化从字符串
/// </summary>
/// <param name= "xml "> xml 字符串 </param>
/// <param name= "type "> 要生成的对象类型 </param>
/// <returns> 反序列化后的对象 </returns>
public static object Deserialize(string xml, Type type)
{
XmlSerializer xs = new XmlSerializer(type);
StringReader sr = new StringReader(xml);
object obj = xs.Deserialize(sr);
sr.Close();
return obj;
}