C#实现对象XML序列化的方法
作者:shichen2014 发布时间:2022-02-11 01:30:59
标签:C#,序列化
本文实例讲述了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;
}
}
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() { }
}
}
//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
}
}
希望本文所述对大家的C#程序设计有所帮助。


猜你喜欢
- # 前言在我们实际项目开发过程中,我们经常需要将不同的两个对象实例进行属性复制,从而基于源对象的属性信息进行后续操作,而不改变源对象的属性信
- 前言:sleep 方法和 wait 方法都是用来将线程进入休眠状态的,并且 sleep 和 wait 方法都可以响应 interrupt 中
- 在主Activity中:listview=(ListView)findViewById(R.id.listview);getData();/
- 在项目中遇到需要批量更新的功能,原本想的是在Java中用循环访问数据库去更新,但是心里总觉得这样做会不会太频繁了,太耗费资源了,效率也很低,
- 前言作为Java开发者,我们每天都会创建大量的对象,但是,我们总是使用管理依赖系统(如Spring框架)来创建这些对象。其实还有其他方法可以
- 前言支付宝推出一个沙箱环境,能够很好的模拟支付宝支付,并且还提供了demo,但demo是一个普通web项目,怎么整合到Spring Boot
- 一、概述 这一章先来点有意思的百度地图应用示例,然后再分章详细介绍用C#开发Android App的各种基本技术。 本章
- 一. switch分支结构1. 简介switch结合case,能够判断一个变量或表达式与一系列值中的某个值是否相等,这里的每个值都被称为一个
- 本文以一个完整实例讲述了C#水印图片的生成方法。是非常实用的技巧。分享给大家供大家参考。具体实例代码如下:/** * 使用说明:
- 引言: 在现代的网络应用程序中,进行HTTP请求是一项常见的任务。Apache HttpClient是一个功能强大且广泛使用的Java库,它
- 本文实例讲述了C#文件合并的方法。分享给大家供大家参考。具体实现方法如下:using System;using System.IO;stri
- 一个线程如何知道另一线程已经结束?Thread类提供了回答此问题的方法。有两种方法可以判定一个线程是否结束。第一,可以在线程中调用isAli
- 原因用Java调用雪球的API,结果返回的是乱码,一番研究后发现是因为返回的数据使用了GZIP压缩,需要先解压才能得到正确数据。思路使用了G
- 这是一个可以从乱码文本中得到正确的原始文本的程序,其基于的原理在于错误的编码往往导致位补充,因此正确的文本使用的字节数应该是最少的(之一)。
- 接着上篇文章,我们继续来学习 Java 中的字节流操作。装饰者缓冲流 BufferedInput/OutputStream装饰者流其实是基于
- 这篇文章主要介绍了基于SPRINGBOOT配置文件占位符过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值
- 零、Gallery的使用回顾我们有时候在iPhone手机上或者Windows上面看到动态的图片,可以通过鼠标或者手指触摸来移动它,产生动态的
- 功能要求: (1)比如每页显示2X2,总共2XN,每个item显示图片+文字(点击有链接)。 如果单行水平滚动,可以用Horizontals
- 第一种方法:获取手机的IMSI码,并判断是中国移动\中国联通\中国电信TelephonyManager telManager = (Tele
- 类型转换Convert.To类型()1、表达式将变量和字面值(在使用运算符时,他们都称作操作数)与运算符组合起来就得到了表达式,它是计算的基