C# XML序列化和反序列化
原文:http://www.cnblogs.com/nhxy/archive/2010/11/16/1878409.html
本文描述如何使用CLR中的StringWriter,XmlSerializer将对象, 对象集合序列化为Xml格式的字符串, 同时描述如何进行反序列化。看代码就能理解,直接上代码了:
案例1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization; namespace ConsoleApplication1
{ class SimpleSerializer { /// <summary> /// 序列化对象 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="t">对象</param> /// <returns></returns> public static string Serialize<T>(T t) { using (StringWriter sw = new StringWriter()) { XmlSerializer xz = new XmlSerializer(t.GetType()); xz.Serialize(sw, t); return sw.ToString(); } } /// <summary> /// 反序列化为对象 /// </summary> /// <param name="type">对象类型</param> /// <param name="s">对象序列化后的Xml字符串</param> /// <returns></returns> public static object Deserialize(Type type, string s) { using (StringReader sr = new StringReader(s)) { XmlSerializer xz = new XmlSerializer(type); return xz.Deserialize(sr); } } }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization; namespace ConsoleApplication1
{ [Serializable] public class UserInfo { private int m_UserId; [XmlElement("userId")] public int UserId { get { return m_UserId; } set { m_UserId = value; } } private string m_UserName; [XmlElement("userName")] public string UserName { get { return m_UserName; } set { m_UserName = value; } } }
}
using System;
using System.Collections.Generic; namespace ConsoleApplication1
{ class Program { static void Main(string[] args) { TestOne(); Console.WriteLine(); TestTwo(); Console.WriteLine(); TestThree(); Console.WriteLine(); TestFour(); Console.ReadLine(); } public static void TestOne() { UserInfo info = new UserInfo() { UserId = 1, UserName = "Guozhijian" }; Console.WriteLine(SimpleSerializer.Serialize<UserInfo>(info)); } public static void TestTwo() { List<UserInfo> list = new List<UserInfo>(); list.Add(new UserInfo() { UserId = 1, UserName = "Guozhijian" }); list.Add(new UserInfo() { UserId = 2, UserName = "Zhenglanzhen" }); Console.WriteLine(SimpleSerializer.Serialize<List<UserInfo>>(list)); } public static void TestThree() { string s = SimpleSerializer.Serialize<UserInfo>(new UserInfo() { UserId = 1, UserName = "Guozhijian" }); UserInfo info = SimpleSerializer.Deserialize(typeof(UserInfo), s) as UserInfo; Console.WriteLine(info.UserId.ToString() + ", " + info.UserName); } public static void TestFour() { List<UserInfo> list = new List<UserInfo>(); list.Add(new UserInfo() { UserId = 1, UserName = "Guozhijian" }); list.Add(new UserInfo() { UserId = 2, UserName = "Zhenglanzhen" }); string s = SimpleSerializer.Serialize<List<UserInfo>>(list); List<UserInfo> newList = SimpleSerializer.Deserialize(typeof(List<UserInfo>), s) as List<UserInfo>; foreach (var info in newList) { Console.WriteLine(info.UserId.ToString() + ", " + info.UserName); } } }
}
运行结果:
案例2:
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"; }
}
[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;
using System.IO;
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(); LoadAsXmlFormat(jbc, "CarData.xml"); 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 Load as XML Format static void LoadAsXmlFormat(object objGraph, string fileName) { XmlSerializer a = new XmlSerializer(objGraph.GetType()); using (StreamReader fStream = new StreamReader(fileName)) { JamesBondCar b = a.Deserialize(fStream) as JamesBondCar; Console.WriteLine("=> Loaded car in XML format!"); Console.WriteLine("Can this car fly? : {0}", b.canFly); } } #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# XML序列化和反序列化相关推荐
- 开心网外挂开发之 XML序列化于反序列化
通过昨天的文章我们已经了解了开发一个开心网的外挂所需要的最基本的东本,接下来的工作可以说基本上就上围绕这个基础来进行的,我写这一系列文章主要的目地不仅仅是为了让大家了解怎么开发开心网外挂,最主要的目过 ...
- XML 序列化与反序列化
XML序列化与反序列化 1.将一个类转化为XML文件 /// <summary>/// 对象序列化成XML文件/// </summary>/// <param name= ...
- XmlSerializer 对象的Xml序列化和反序列化,XMLROOT别名设置
这篇随笔对应的.Net命名空间是System.Xml.Serialization:文中的示例代码需要引用这个命名空间. 为什么要做序列化和反序列化? .Net程序执行时,对象都驻留在内存中:内存中的对 ...
- Xml序列化、反序列化帮助类
之前从网络上找了一个Xml处理帮助类,并整理了一下,这个帮助类针对Object类型进行序列化和反序列化,而不需要提前定义Xml的结构,把它放在这儿供以后使用 1 /// <summary> ...
- XML序列化和反序列化(C#)
主要参考资料: http://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part-1 http ...
- [WPF]xml序列化以及反序列化数据
代码 XML序列化工具类 public static class XMLHelper{/// <summary>/// 将对象序列化为指定的文件名/// </summary>/ ...
- C# XML 序列化 及 反序列化
百科:序列化 (Serialization)将对象的状态信息转换为可以存储或传输的形式的过程.在序列化期间,对象将其当前状态写入到临时或持久性存储区.以后,可以通过从存储区中读取或反序列化对象的状态, ...
- ASP.NET 对类进行XML序列化和反序列化
1 序列化方法 public void SerializeObject<T>(string Xmlname,T t){XmlSerializer ser = new XmlSerializ ...
- XML序列化和反序列化 以及相关类的写法
类的写法: 省网办数据对接中运用到 using System; using System.Collections.Generic; using System.Linq; using System.Te ...
最新文章
- 谁会为小扎的AI管家配音:网民选了这位老帅哥
- java基础(5)----面向对象
- JAVA窗口sin值_大厂经典笔试题—LeetCode03无重复字符的最长子串(滑动窗口)
- 完全理解NIO Selector
- 云原生系列「四」我为啥不看好ServiceMesh?
- 在Eclispe中编译运行jbox2d
- 动态规划|Dynamic Programming
- sun.misc.BASE64Decoder导入异常及处理思路
- 如何才能不被社会淘汰?一个程序员的七年之痒
- HIbernate学习笔记5 之 查询
- 181101每日一句
- php读取excel写入数据库,PHP读取EXCEL文件写入数据库
- Windows修改键盘映射
- STC单片机使用RS485下载程序方法
- 经验模态分解(Empirical Mode Decomposition ,EMD)特征提取及其原理
- 如何鉴定光缆质量好坏?
- 互联网大厂职级对应薪资一览表
- JPEG文件格式分析及举例验证
- canvas 画图 android,Android 中的Canvas画图
- HTLM 零基础入门教程(详解)