您的位置:首页 > 其它

序列化(serialization) & 反序列化(de-serialization)- 序列化到内存xml

2008-08-08 17:46 495 查看
序列化:提供了可以把内存中的对象的snapshot保存到xml,二进制文件,内存的机制;

在需要的时候,可以用反序列化就可以得到当时的 snapshot

----------------------------------------------------------
最近在做项目的时候,需要把一个List 序列化到内存中,但是以XML格式。

经过一定的research and try 终于解决问题啦:

假设这里有一个list需要序列化:

List<Person> List = GetList();

XmlSerializer xs = new XmlSerializer(typeof(List<Person>)
, new Type[] { typeof(PersonAttribute)});
//atra types input here

MemoryStream ms = new MemoryStream();

//序列化到内存流,这个时候是字节
xs.Serialize(ms, FilterEntryList);

byte[] content = new byte[ms.Length];

ms.Position = 0;//this is important, you should reset the pointer
ms.Read(content, 0, (int)ms.Length);
//(int)ms.Length, here you can do further processing in case the length too large to miss some bytes data
//change the encoding
ASCIIEncoding ae = new ASCIIEncoding();
string XmlContent = ae.GetString(content);

//load the string to xmldocument
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(XmlContent);

//then you have get a xmldocument in memory

wisdom
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: