-
C#教程之C#实现对象XML序列化的方法
本文实例讲述了C#实现对象XML序列化的方法。分享给大家供大家参考。具体实现方法如下:
复制代码 代码如下:
using system;
using system.xml;
using system.xml.serialization;
using system.text;
using system.io;
public class util
{
/// <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;
}
}
using system.xml;
using system.xml.serialization;
using system.text;
using system.io;
public class util
{
/// <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;
}
}
stringwriter,xmlserializer将对象、对象集合序列化为xml格式的字符串, 同时描述如何进行反序列化.
c# 序列化 xmlserializer,binaryformatter,soapformatter
复制代码 代码如下:
//radio.cs
using system;
using system.collections.generic;
using system.text;
namespace simpleserialize
{
[serializable]
public class radio
{
public bool hastweeters;
public bool hassubwoofers;
public double[] stationpresets;
[nonserialized]
public string radioid = "xf-552rr6";
}
}
//cars.cs
using system;
using system.collections.generic;
using system.text;
using system.xml.serialization;
namespace simpleserialize
{
[serializable]
public class car
{
public radio theradio = new radio();
public bool ishatchback;
}
[serializable, xmlroot(namespace = "http://www.intertech.com")]
public class jamesbondcar : car
{
[xmlattribute]
public bool canfly;
[xmlattribute]
public bool cansubmerge;
public jamesbondcar(bool skyworthy, bool seaworthy)
{
canfly = skyworthy;
cansubmerge = seaworthy;
}
// the xmlserializer demands a default constructor!
public jamesbondcar() { }
}
}
using system;
using system.collections.generic;
using system.text;
namespace simpleserialize
{
[serializable]
public class radio
{
public bool hastweeters;
public bool hassubwoofers;
public double[] stationpresets;
[nonserialized]
public string radioid = "xf-552rr6";
}
}
//cars.cs
using system;
using system.collections.generic;
using system.text;
using system.xml.serialization;
namespace simpleserialize
{
[serializable]
public class car
{
public radio theradio = new radio();
public bool ishatchback;
}
[serializable, xmlroot(namespace = "http://www.intertech.com")]
public class jamesbondcar : car
{
[xmlattribute]
public bool canfly;
[xmlattribute]
public bool cansubmerge;
public jamesbondcar(bool skyworthy, bool seaworthy)
{
canfly = skyworthy;
cansubmerge = seaworthy;
}
// the xmlserializer demands a default constructor!
public jamesbondcar() { }
}
}
复制代码 代码如下:
//program.cs
using system;
using system.collections.generic;
using system.text;
using system.io;
// for the formatters.
using system.runtime.serialization.formatters.binary;
using system.runtime.serialization.formatters.soap;
using system.xml.serialization;
namespace simpleserialize
{
class program
{
static void main(string[] args)
{
console.writeline("***** fun with object serialization *****n");
// make a jamesbondcar and set state.
jamesbondcar jbc = new jamesbondcar();
jbc.canfly = true;
jbc.cansubmerge = false;
jbc.theradio.stationpresets = new double[] { 89.3, 105.1, 97.1 };
jbc.theradio.hastweeters = true;
// now save / load the car to a specific file.
saveasbinaryformat(jbc, "cardata.dat");
loadfrombinaryfile("cardata.dat");
saveassoapformat(jbc, "cardata.soap");
saveasxmlformat(jbc, "cardata.xml");
savelistofcars();
savelistofcarsasbinary();
console.readline();
}
#region save / load as binary format
static void saveasbinaryformat(object objgraph, string filename)
{
// save object to a file named cardata.dat in binary.
binaryformatter binformat = new binaryformatter();
using (stream fstream = new filestream(filename,
filemode.create, fileaccess.write, fileshare.none))
{
binformat.serialize(fstream, objgraph);
}
console.writeline("=> saved car in binary format!");
}
static void loadfrombinaryfile(string filename)
{
binaryformatter binformat = new binaryformatter();
// read the jamesbondcar from the binary file.
using (stream fstream = file.openread(filename))
{
jamesbondcar carfromdisk =
(jamesbondcar)binformat.deserialize(fstream);
console.writeline("can this car fly? : {0}", carfromdisk.canfly);
}
}
#endregion
#region save as soap format
// be sure to import system.runtime.serialization.formatters.soap
// and reference system.runtime.serialization.formatters.soap.dll.
static void saveassoapformat(object objgraph, string filename)
{
// save object to a file named cardata.soap in soap format.
soapformatter soapformat = new soapformatter();
using (stream fstream = new filestream(filename,
filemode.create, fileaccess.write, fileshare.none))
{
soapformat.serialize(fstream, objgraph);
}
console.writeline("=> saved car in soap format!");
}
#endregion
#region save as xml format
static void saveasxmlformat(object objgraph, string filename)
{
// save object to a file named cardata.xml in xml format.
xmlserializer xmlformat = new xmlserializer(typeof(jamesbondcar),
new type[] { typeof(radio), typeof(car) });
using (stream fstream = new filestream(filename,
filemode.create, fileaccess.write, fileshare.none))
{
xmlformat.serialize(fstream, objgraph);
}
console.writeline("=> saved car in xml format!");
}
#endregion
#region save collection of cars
static void savelistofcars()
{
// now persist a list<> of jamesbondcars.
list<jamesbondcar> mycars = new list<jamesbondcar>();
mycars.add(new jamesbondcar(true, true));
mycars.add(new jamesbondcar(true, false));
mycars.add(new jamesbondcar(false, true));
mycars.add(new jamesbondcar(false, false));
using (stream fstream = new filestream("carcollection.xml",
filemode.create, fileaccess.write, fileshare.none))
{
xmlserializer xmlformat = new xmlserializer(typeof(list<jamesbondcar>),
new type[] { typeof(jamesbondcar), typeof(car), typeof(radio) });
xmlformat.serialize(fstream, mycars);
}
console.writeline("=> saved list of cars!");
}
static void savelistofcarsasbinary()
{
// save arraylist object (mycars) as binary.
list<jamesbondcar> mycars = new list<jamesbondcar>();
binaryformatter binformat = new binaryformatter();
using (stream fstream = new filestream("allmycars.dat",
filemode.create, fileaccess.write, fileshare.none))
{
binformat.serialize(fstream, mycars);
}
console.writeline("=> saved list of cars in binary!");
}
#endregion
}
}
using system;
using system.collections.generic;
using system.text;
using system.io;
// for the formatters.
using system.runtime.serialization.formatters.binary;
using system.runtime.serialization.formatters.soap;
using system.xml.serialization;
namespace simpleserialize
{
class program
{
static void main(string[] args)
{
console.writeline("***** fun with object serialization *****n");
// make a jamesbondcar and set state.
jamesbondcar jbc = new jamesbondcar();
jbc.canfly = true;
jbc.cansubmerge = false;
jbc.theradio.stationpresets = new double[] { 89.3, 105.1, 97.1 };
jbc.theradio.hastweeters = true;
// now save / load the car to a specific file.
saveasbinaryformat(jbc, "cardata.dat");
loadfrombinaryfile("cardata.dat");
saveassoapformat(jbc, "cardata.soap");
saveasxmlformat(jbc, "cardata.xml");
savelistofcars();
savelistofcarsasbinary();
console.readline();
}
#region save / load as binary format
static void saveasbinaryformat(object objgraph, string filename)
{
// save object to a file named cardata.dat in binary.
binaryformatter binformat = new binaryformatter();
using (stream fstream = new filestream(filename,
filemode.create, fileaccess.write, fileshare.none))
{
binformat.serialize(fstream, objgraph);
}
console.writeline("=> saved car in binary format!");
}
static void loadfrombinaryfile(string filename)
{
binaryformatter binformat = new binaryformatter();
// read the jamesbondcar from the binary file.
using (stream fstream = file.openread(filename))
{
jamesbondcar carfromdisk =
(jamesbondcar)binformat.deserialize(fstream);
console.writeline("can this car fly? : {0}", carfromdisk.canfly);
}
}
#endregion
#region save as soap format
// be sure to import system.runtime.serialization.formatters.soap
// and reference system.runtime.serialization.formatters.soap.dll.
static void saveassoapformat(object objgraph, string filename)
{
// save object to a file named cardata.soap in soap format.
soapformatter soapformat = new soapformatter();
using (stream fstream = new filestream(filename,
filemode.create, fileaccess.write, fileshare.none))
{
soapformat.serialize(fstream, objgraph);
}
console.writeline("=> saved car in soap format!");
}
#endregion
#region save as xml format
static void saveasxmlformat(object objgraph, string filename)
{
// save object to a file named cardata.xml in xml format.
xmlserializer xmlformat = new xmlserializer(typeof(jamesbondcar),
new type[] { typeof(radio), typeof(car) });
using (stream fstream = new filestream(filename,
filemode.create, fileaccess.write, fileshare.none))
{
xmlformat.serialize(fstream, objgraph);
}
console.writeline("=> saved car in xml format!");
}
#endregion
#region save collection of cars
static void savelistofcars()
{
// now persist a list<> of jamesbondcars.
list<jamesbondcar> mycars = new list<jamesbondcar>();
mycars.add(new jamesbondcar(true, true));
mycars.add(new jamesbondcar(true, false));
mycars.add(new jamesbondcar(false, true));
mycars.add(new jamesbondcar(false, false));
using (stream fstream = new filestream("carcollection.xml",
filemode.create, fileaccess.write, fileshare.none))
{
xmlserializer xmlformat = new xmlserializer(typeof(list<jamesbondcar>),
new type[] { typeof(jamesbondcar), typeof(car), typeof(radio) });
xmlformat.serialize(fstream, mycars);
}
console.writeline("=> saved list of cars!");
}
static void savelistofcarsasbinary()
{
// save arraylist object (mycars) as binary.
list<jamesbondcar> mycars = new list<jamesbondcar>();
binaryformatter binformat = new binaryformatter();
using (stream fstream = new filestream("allmycars.dat",
filemode.create, fileaccess.write, fileshare.none))
{
binformat.serialize(fstream, mycars);
}
console.writeline("=> saved list of cars in binary!");
}
#endregion
}
}
希望本文所述对大家的C#程序设计有所帮助。
栏目列表
最新更新
python爬虫及其可视化
使用python爬取豆瓣电影短评评论内容
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比