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

本文介绍了一种将List<Person>对象序列化为XML格式的方法,并详细展示了使用C#进行内存序列化的具体步骤。通过实例演示了如何创建XmlSerializer实例、序列化对象到内存流,以及如何从内存流读取并转换为XML字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


 序列化:提供了可以把内存中的对象的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

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值