C#中XML与对象之间的序列化、反序列化
直接上代码:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization; namespace Xml.Utility
{
public static class XmlUtil
{
/// <summary>
/// 将一个对象序列化为XML字符串
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>序列化产生的XML字符串</returns>
public static string XmlSerialize(object o, Encoding encoding)
{
if (o == null)
{
throw new ArgumentNullException("o");
} if (encoding == null)
{
throw new ArgumentNullException("encoding");
} using (MemoryStream stream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(o.GetType()); XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineChars = "\r\n";
settings.Encoding = encoding;
settings.IndentChars = " ";
settings.OmitXmlDeclaration = true; using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
serializer.Serialize(writer, o, ns);
writer.Close();
} stream.Position = ;
using (StreamReader reader = new StreamReader(stream, encoding))
{
return reader.ReadToEnd();
}
}
} /// <summary>
/// 从XML字符串中反序列化对象
/// </summary>
/// <typeparam name="T">结果对象类型</typeparam>
/// <param name="s">包含对象的XML字符串</param>
/// <param name="encoding">编码方式</param>
/// <returns>反序列化得到的对象</returns>
public static T XmlDeserialize<T>(string s, Encoding encoding)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentNullException("s");
if (encoding == null)
throw new ArgumentNullException("encoding"); XmlSerializer mySerializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
{
using (StreamReader sr = new StreamReader(ms, encoding))
{
return (T)mySerializer.Deserialize(sr);
}
}
} /// <summary>
/// 将一个对象按XML序列化的方式写入到一个文件
/// </summary>
/// <param name="o">要序列化的对象</param>
/// <param name="path">保存文件路径</param>
/// <param name="encoding">编码方式</param>
public static void XmlSerializeToFile(object o, string path, Encoding encoding)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
} if (o == null)
{
throw new ArgumentNullException("o");
} if (encoding == null)
{
throw new ArgumentNullException("encoding");
} using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
{
XmlSerializer serializer = new XmlSerializer(o.GetType()); XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.NewLineChars = "\r\n";
settings.Encoding = encoding;
settings.IndentChars = " "; using (XmlWriter writer = XmlWriter.Create(file, settings))
{
serializer.Serialize(writer, o);
writer.Close();
}
}
} /// <summary>
/// 读入一个文件,并按XML的方式反序列化对象。
/// </summary>
/// <typeparam name="T">结果对象类型</typeparam>
/// <param name="path">文件路径</param>
/// <param name="encoding">编码方式</param>
/// <returns>反序列化得到的对象</returns>
public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding"); string xml = File.ReadAllText(path, encoding);
return XmlDeserialize<T>(xml, encoding);
}
}
}
C#中XML与对象之间的序列化、反序列化的更多相关文章
- php中 xml json 数组 之间相互转换
php中 xml json 数组 之间相互转换 1 数组转json $result = array( 'status' =>$status, 'message'=>$message, ' ...
- Java中字节与对象之间的转换
近期公司里面用到了消息队列,而正如我们知道的是消息队列之间的是通过二进制形式的.以下就分享一下java中字节与对象之间的转换. 主要是用到了ByteArrayOutputStream和ObjectOu ...
- java中Xml、json之间的相互转换
旁白: 最近关于xml与json之间的转换都搞蒙了,这里写一个demo,以后备用. 正题: project格式是: jar包是一个一个检出来的,还算干净了. 代码: 工具类: package exer ...
- 关于spring中请求返回值的json序列化/反序列化问题
https://cloud.tencent.com/developer/article/1381083 https://www.jianshu.com/p/db07543ffe0a 先留个坑
- C#中关于XML与对象,集合的相互转换
XML与对象,集合的相互转化 今天小伙伴在群里问了一下关于XML与对象之间的相互转换,作为菜鸟的我正好趁着闲着的时间学习了一波,直接上代码了,有疑问或者有错误的地方还请大家指正,谢谢.... usin ...
- .NET中XML序列化和反序列化常用类和用来控制XML序列化的属性总结(XmlSerializer,XmlTypeAttribute,XmlElementAttribute,XmlAttributeAttribute,XmlArrayAttribute...)
序列化和反序列化是指什么? 序列化(seriallization): 将对象转化为便于传输的数据格式, 常见的序列化格式:二进制格式,字节数组,json字符串,xml字符串.反序列化(deserial ...
- php json与xml序列化/反序列化
在web开发中对象的序列化与反序列化经常使用,比较主流的有json格式与xml格式的序列化与反序列化,今天想写个jsop的小demo,结果发现不会使用php序列化,查了一下资料,做个笔记 简单数组js ...
- .net 序列化反序列化
.net 序列化创建对象的深拷贝 public static object DeepClone(object original) { using (MemoryStream stream = new ...
- .net的XML对象序列化VS WCF中xml序列化问题
整理一下 .net 对象序列化注意事项: 1. 字段:必须是 public类型 2.属性:只读或者只写的属性不被序列化,只有 可读可写并且赋值的才可以 序列化: Someclass obj = new ...
随机推荐
- 文件拷贝以及base64
File inFile = new File("d:" + File.separator + "test.jpg"); File outFile = new F ...
- web APi角色认证
http://www.cnblogs.com/youring2/archive/2013/03/09/2950992.html http://kb.cnblogs.com/page/107117/
- [hihoCoder]#1039 : 字符消除
Description 小Hi最近在玩一个字符消除游戏.给定一个只包含大写字母"ABC"的字符串s,消除过程是如下进行的: 1)如果s包含长度超过1的由相同字母组成的子串,那么这些 ...
- VS 2010下单元测试
1.创建单元测试项目 2.创建完成后,新建项目会自动添加“Microsoft.VisualStudio.QualityTools.UnitTestFramework”的引用,该引用用于单元 ...
- opennebula 出错截图与调试
- 闲话Cache:始篇
Caching(缓存)在现代的计算机系统中是一项最古老最基本的技术.它存在于计算机各种硬件和软件系统中,比如各种CPU, 存储系统(IBM ESS, EMC Symmetrix…),数据库,Web服务 ...
- How to Send Information (String, Image, Record) Between Two Applications
http://delphi.about.com/od/windowsshellapi/a/wm_copydata.htm here are many situation when you need t ...
- Java组各任务工作流程
1.周枫 A.提供基于SQL SERVER的数据库基本表结构创建脚本,基础数据脚本,按学科(产品)的数据脚本. 2.吴缤 A.提供给周茉的安装包用的项目文件,共三个digital,xylinkWeb和 ...
- 【JavaScript】Registering JavaScript object methods as callbacks
The registration of callback functions is very common in JavaScript web programming, for example to ...
- HDU 5019 Revenge of GCD(数学)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5019 Problem Description In mathematics, the greatest ...