標籤:serialize sum article pop gets stringbu blog writer object
原文:http://blog.csdn.net/otong/article/details/7894059
序列化或還原序列化成一個字串:
方法一:
序列化:
[csharp] view plain copy
- public static string XMLSerialize<T>(T entity)
- {
- StringBuilder buffer = new StringBuilder();
-
- XmlSerializer serializer = new XmlSerializer(typeof(T));
- using (TextWriter writer = new StringWriter(buffer))
- {
- serializer.Serialize(writer, entity);
- }
-
- return buffer.ToString();
-
- }
還原序列化:
[csharp] view plain copy
- public static T DeXMLSerialize<T>(string xmlString)
- {
- T cloneObject = default(T);
-
- StringBuilder buffer = new StringBuilder();
- buffer.Append(xmlString);
-
- XmlSerializer serializer = new XmlSerializer(typeof(T));
-
- using (TextReader reader = new StringReader(buffer.ToString()))
- {
- Object obj = serializer.Deserialize(reader);
- cloneObject = (T)obj;
- }
-
- return cloneObject;
- }
方法二:
[csharp] view plain copy
- /// <summary>
- /// 對象序列化成 XML String
- /// </summary>
- public static string XmlSerialize<T>(T obj)
- {
- string xmlString = string.Empty;
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- using (MemoryStream ms = new MemoryStream())
- {
- xmlSerializer.Serialize(ms, obj);
- xmlString = Encoding.UTF8.GetString(ms.ToArray());
- }
- return xmlString;
- }
-
- /// <summary>
- /// XML String 還原序列化成對象
- /// </summary>
- public static T XmlDeserialize<T>(string xmlString)
- {
- T t = default(T);
- XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
- using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
- {
- using (XmlReader xmlReader = XmlReader.Create(xmlStream))
- {
- Object obj = xmlSerializer.Deserialize(xmlReader);
- t = (T)obj;
- }
- }
- return t;
- }
如果要序列化到一個檔案,則使用FileStream就可以了
如:
string strFile = @"c:/book.xml";
using (FileStream fs = new FileStream(strFile, FileMode.Create))
{
XmlSerializer formatter = new XmlSerializer(typeof(T));
formatter.Serialize(fs, entity);
}
附:其實還可以直接用SringWriter
StringBuilder sb = new StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
XmlSerializer formatter = new XmlSerializer(typeof(T));
formatter .Serialize(writer,entity );
一個可序列化的C#對象,如何轉成一個XML格式的檔案或字串【轉】