Xml序列化和反序列化对象-使用MemoryStream-实践
【目的】
实践MemoryStream来Xml序列化对象
【代码】
待序列化类:
[Serializable()]
public class XInfo
{
private int _ID;
private string _Content;
public XInfo()
{
_ID = 0;
_Content = "Hello";
}
public int ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}
public string Content
{
get
{
return _Content;
}
set
{
_Content = value;
}
}
}
序列化对象和反序列化代码
System.Text.StringBuilder sb = new System.Text.StringBuilder();
XInfo myBlock = new XInfo();
XmlSerializer mySerializer = new XmlSerializer(typeof(XInfo));
using (Stream mem = new MemoryStream())
{
mySerializer.Serialize(mem, myBlock);
byte[] b = new byte[mem.Length];
mem.Position = 0;
mem.Read(b, 0, b.Length);
sb.Append(System.Text.UTF8Encoding.UTF8.GetString(b));
}
Response.Write(sb.ToString());
XInfo myObject;
XmlSerializer myDeSerializer = new XmlSerializer(typeof(XInfo));
Stream DesMem = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(sb.ToString()));
myObject = (XInfo)myDeSerializer.Deserialize(DesMem);
if (myObject != null)
{
myObject.ID = 100;
Response.Write(myObject.ID);
Response.Write(myObject.Content);
}
else
Response.Write("Null");
DesMem.Close();
结论:正确执行,暂无异常
无论生活、还是技术,一切都不断的学习和更新~~~努力~