基本.NET浅串行化
2008-08-12 00:27 Kevin-wang 阅读(240) 评论(0) 编辑 收藏 举报
浅串行化:只串行化类的公共字段和属性
公共属性必须是可读且可写的
使用命名空间:using System.Xml.Serialization;
以Book类为例:
串行化模板:
反串行化模板:
*使用XmlSerializer的类必须有一个不带参数的默认构造函数——在反串行化中使用
*序列化ArrayList类型字段X的特殊处理:在ctor中 this.X = new ArrayList();
*对于引用关系,如果A中引用了B,那么
在序列化A的时候,会生成如下格式的XML:
<A>
<B>xxxxx</B>
</A>
在反序列化A对象的时候,A中也会包含有具体值的B对象
*浅序列化不支持循环引用,即A引用B的同时,B也引用了A
序列化时,将XML格式定制为SOAP格式:使用XmlSerializer构造函数的另一个重载:
公共属性必须是可读且可写的
使用命名空间:using System.Xml.Serialization;
以Book类为例:
串行化模板:
public void SerializeIt(string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(Book));
StreamWriter writer = new StreamWriter(filename);
Book myBook = new Book();
serializer.Serialize(writer, myBook);
writer.Close();
}
{
XmlSerializer serializer = new XmlSerializer(typeof(Book));
StreamWriter writer = new StreamWriter(filename);
Book myBook = new Book();
serializer.Serialize(writer, myBook);
writer.Close();
}
反串行化模板:
public void DeserializeIt(string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(Book));
FileStream fs = new FileStream(filename, FileMode.Open);
Book myBook = (Book)serializer.Deserialize(fs);
fs.Close();
}
{
XmlSerializer serializer = new XmlSerializer(typeof(Book));
FileStream fs = new FileStream(filename, FileMode.Open);
Book myBook = (Book)serializer.Deserialize(fs);
fs.Close();
}
*使用XmlSerializer的类必须有一个不带参数的默认构造函数——在反串行化中使用
*序列化ArrayList类型字段X的特殊处理:在ctor中 this.X = new ArrayList();
*对于引用关系,如果A中引用了B,那么
在序列化A的时候,会生成如下格式的XML:
<A>
<B>xxxxx</B>
</A>
在反序列化A对象的时候,A中也会包含有具体值的B对象
*浅序列化不支持循环引用,即A引用B的同时,B也引用了A
序列化时,将XML格式定制为SOAP格式:使用XmlSerializer构造函数的另一个重载:
public void SerializeIt(string filename)
{
SoapReflectionImporter import = new SoapReflectionImporter();
XmlTypeMapping soapMapping = import.ImportTypeMapping(typeof(Book));
XmlSerializer serializer = new XmlSerializer(soapMapping);
StreamWriter writer = new StreamWriter(filename);
Book myBook = new Book();
serializer.Serialize(writer, myBook);
writer.Close();
}
{
SoapReflectionImporter import = new SoapReflectionImporter();
XmlTypeMapping soapMapping = import.ImportTypeMapping(typeof(Book));
XmlSerializer serializer = new XmlSerializer(soapMapping);
StreamWriter writer = new StreamWriter(filename);
Book myBook = new Book();
serializer.Serialize(writer, myBook);
writer.Close();
}