C# 中xml数组的序列和反序列化方法
先来看xml
<?xml version='1.0'?> <root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><Person><Name>小莫</Name><Age>20</Age><Books><Book><Title>马列主义</Title><ISBN>SOD1323DS</ISBN></Book><Book><Title>高等数学</Title><ISBN>SOD1S8374</ISBN></Book></Books></Person><Person><Name>小红</Name><Age>20</Age><Books><Book><Title>思想</Title><ISBN>SID1323D845</ISBN></Book></Books></Person> </root>
这个xml包含多个Person对象,每个Person对象又包含一个Books对象和多个book对象,反序列化XML时关键是看怎么理解xml的结构,理解正确了就很好构造对应的类,理解错了可能就陷入坑里。
首先root是整个文件的根节点,它是由多个Person组成的。
[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)][System.Xml.Serialization.XmlRootAttribute("root", IsNullable = false)]public class BaseInfo{[System.Xml.Serialization.XmlElementAttribute("Person")]public List<Person> PersonList { get; set; }}
再看Person对象,Person是由name和age两个属性和一个Books对象组成,Person可以定义成
[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)][System.Xml.Serialization.XmlRootAttribute("Person", IsNullable = false)]public class Person{public string Name { get; set; }public int Age { get; set; }[System.Xml.Serialization.XmlElementAttribute("Books")]public Books Books { get; set; }}
这里理解的关键是把下面这小段xml理解成一个包含多个Book的对象,而不是把它理解成book的数组
<Books><Book><Title>毛泽思想</Title><ISBN>SID1323DSD</ISBN></Book></Books>
如果把她理解成一个数据就容易把Person定义成
[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)][System.Xml.Serialization.XmlRootAttribute("Person", IsNullable = false)]public class Person{public string Name { get; set; }public int Age { get; set; }[System.Xml.Serialization.XmlElementAttribute("Books")]public List<Book> Books { get; set; }}
而book的定义如下
[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)][System.Xml.Serialization.XmlRootAttribute("Book", IsNullable = false)]public class Book{public string Title { get; set; }public string ISBN { get; set; }}
序列化生成的xml不包含Book节点
,生成的xml如下
<?xml version="1.0"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Person><Name>小莫</Name><Age>20</Age><Books><Title>马列主义</Title><ISBN>SOD1323DS</ISBN></Books></Person><Person><Name>小红</Name><Age>20</Age><Books><Title>毛泽思想</Title><ISBN>SID1323DSD</ISBN></Books></Person> </root>
之所以出现上面的情况是因为:
public List<Book> Books { get; set; } 和Book同属一个节点层次,在List<Book> Books上显式指定了属性名称Books,那么这个节点就是Books,跟Book上定义指定的[System.Xml.Serialization.XmlRootAttribute("Book", IsNullable = false)] 没有关系,它是用来指示Book是跟节点时的名称。 或者可以这样理解xml是由多个节点组成的,而Book类定义不是一个节点,它只是一个定义,要想xml中出现book,就需要再加一个节点,我们把Person节点加到Books对象中
[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]public class Books{[System.Xml.Serialization.XmlElementAttribute("Book")]public List<Book> BookList { get; set; }}
这样就多出了一个节点,再结合刚开始的person定义就能序列化出正确的xml了
完整的代码
[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)][System.Xml.Serialization.XmlRootAttribute("root", IsNullable = false)]public class BaseInfo{[System.Xml.Serialization.XmlElementAttribute("Person")]public List<Person> PersonList { get; set; }}[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)][System.Xml.Serialization.XmlRootAttribute("Person", IsNullable = false)]public class Person{public string Name { get; set; }public int Age { get; set; }[System.Xml.Serialization.XmlElementAttribute("Books")]public Books Books { get; set; }}[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]public class Books{[System.Xml.Serialization.XmlElementAttribute("Book")]public List<Book> BookList { get; set; }}[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)][System.Xml.Serialization.XmlRootAttribute("Book", IsNullable = false)]public class Book{public string Title { get; set; }public string ISBN { get; set; }}
static void Main(string[] args){BaseInfo baseInfo = new BaseInfo();List<Person> personList = new List<Person>();Person p1 = new Person();p1.Name = "小莫";p1.Age = 20;List<Book> books = new List<Book>();Book book = new Book();book.Title = "马列主义";book.ISBN = "SOD1323DS";books.Add(book);p1.Books = new Books();p1.Books.BookList = books;Person p2 = new Person();p2.Name = "小红";p2.Age = 20;List<Book> books2 = new List<Book>();Book book2 = new Book();book2.Title = "毛泽思想";book2.ISBN = "SID1323DSD";books2.Add(book2);p2.Books =new Books();p2.Books.BookList = books2;personList.Add(p1);personList.Add(p2);baseInfo.PersonList = personList;string postXml2 = SerializeHelper.Serialize(typeof(BaseInfo), baseInfo);Console.ReadLine();}}
序列化用到的类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.IO; using System.Xml;namespace ConsoleApplication1 {public class SerializeHelper{public static string Serialize(Type type, object o){string result = string.Empty;try{XmlSerializer xs = new XmlSerializer(type);MemoryStream ms = new MemoryStream();xs.Serialize(ms, o);ms.Seek(0, SeekOrigin.Begin);StreamReader sr = new StreamReader(ms);result = sr.ReadToEnd();ms.Close();}catch (Exception ex){throw new Exception("对象序列化成xml时发生错误:" + ex.Message);}return result;}/// <summary>/// 序列化XML时不带默认的命名空间xmlns/// </summary>/// <param name="type"></param>/// <param name="o"></param>/// <returns></returns>public static string SerializeNoneNamespaces(Type type, object o){string result = string.Empty;try{XmlSerializer xs = new XmlSerializer(type);MemoryStream ms = new MemoryStream();XmlSerializerNamespaces ns = new XmlSerializerNamespaces();ns.Add("", "");//Add an empty namespace and empty valuexs.Serialize(ms, o, ns);ms.Seek(0, SeekOrigin.Begin);StreamReader sr = new StreamReader(ms);result = sr.ReadToEnd();ms.Close();}catch (Exception ex){throw new Exception("对象序列化成xml时发生错误:" + ex.Message);}return result;}/// <summary>/// 序列化时不生成XML声明和XML命名空间/// </summary>/// <param name="type"></param>/// <param name="o"></param>/// <returns></returns>public static string SerializeNoNamespacesNoXmlDeclaration(Type type, object o){string result = string.Empty;try{XmlSerializer xs = new XmlSerializer(type);MemoryStream ms = new MemoryStream();XmlSerializerNamespaces ns = new XmlSerializerNamespaces();XmlWriterSettings settings = new XmlWriterSettings();settings.OmitXmlDeclaration = true;//不编写XML声明XmlWriter xmlWriter = XmlWriter.Create(ms, settings);ns.Add("", "");//Add an empty namespace and empty valuexs.Serialize(xmlWriter, o, ns);ms.Seek(0, SeekOrigin.Begin);StreamReader sr = new StreamReader(ms);result = sr.ReadToEnd();ms.Close();}catch (Exception ex){throw new Exception("对象序列化成xml时发生错误:" + ex.Message);}return result;}public static object Deserialize(Type type, string xml){object root = new object();try{XmlSerializer xs = new XmlSerializer(type);MemoryStream ms = new MemoryStream();StreamWriter sw = new StreamWriter(ms);sw.Write(xml);sw.Flush();ms.Seek(0, SeekOrigin.Begin);root = xs.Deserialize(ms);ms.Close();}catch (Exception ex){throw new Exception("xml转换成对象时发生错误:" + ex.Message);}return root;}} }
再看一个例子,简单数组类型的序列化
<?xml version="1.0"?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><barcodes><barcode>AAA</barcode><barcode>BBB</barcode></barcodes> </root>
我们经常搞半天不知道要怎么书写上面xml对应的类,总是容易出现上面说过的错误,关键还是看怎么理解barcodes,和上面的例子类似,这里只写类怎么创建
[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)][System.Xml.Serialization.XmlRootAttribute("root", IsNullable = false)]public class DownLoadPDFRequest{[System.Xml.Serialization.XmlElementAttribute("barcodes")]public barcoders barcodes { get; set; }}[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]//[System.Xml.Serialization.XmlRootAttribute("barcoders", IsNullable = false)]public class barcoders{private List<string> _barcode;[System.Xml.Serialization.XmlElementAttribute("barcode")]public List<string> BarCode{get { return _barcode; }set { _barcode = value; }}}
static void Main(string[] args){DownLoadPDFRequest request = new DownLoadPDFRequest();List<barcoders> barcodes = new List<barcoders>();List<string> bars=new List<string>();bars.Add("AAA");bars.Add("BBB");request.barcodes = new barcoders();;request.barcodes.BarCode = bars;string postXml = SerializeHelper.Serialize(typeof(DownLoadPDFRequest), request); }
C# 中xml数组的序列和反序列化方法相关推荐
- js中的数组Array定义与sort方法使用示例
js中的数组Array定义与sort方法使用示例 Array的定义及sort方法使用示例 Array数组相当于java中的ArrayList 定义方法: 1:使用new Array(5 )创建数 ...
- JavaScript中的数组遍历forEach()与map()方法以及兼容写法
原理: 高级浏览器支持forEach方法 语法:forEach和map都支持2个参数:一个是回调函数(item,index,list)和上下文: forEach:用来遍历数组中的每一项:这个方法执行是 ...
- map语法获取index_JavaScript中的数组遍历forEach()与map()方法以及兼容写法
原理: 高级浏览器支持forEach方法 语法:forEach和map都支持2个参数:一个是回调函数(item,index,list)和上下文: forEach:用来遍历数组中的每一项:这个方法执行是 ...
- c语言中创建一个整数数组_VBA中动态数组的创建及利用方法
大家好,后疫情时代一定会到来,各行各业,都将是一场战胜萧条的无声的战役.无论怎样,我们一定要坚信,疫情终将会过去,曙光一定会到来.后疫情时代将会是一个全新的世界,很多理念都将被打破,大多数人不会再享受 ...
- js中的数组和字符串的一些方法
数组的一些方法: 1.join()和split()方法 <script type="text/javascript"> var x; var a=new Array() ...
- php if为空那么,PHP中判断数组是否为空的方法
PHP中判断数组为空的方法有好几种,但当遇到判断多维数组时,这些方法都无法判别数组是否为空,现在下面先介绍从网上搜索到判断一维数组的方法. PHP判断数组为空之一.for循环 最简单也是最直接的方法, ...
- Vue中构造数组数据-map和forEach方法梳理
数组操作是前端最重要的数据操作,构造数组数据,又是数组操作中很常见的.本文将梳理下map和forEach方法在Vue项目中的使用. 想要深入理解这两个方法,一定要手写几次简易的实现,理解其中的要义.这 ...
- Java中的数组与List相互转换的方法分析
目录 一.Java中的数组转换为List的方法 1.使用Arrays.asList()方法 2.使用Collections.addAll()方法 3.使用集合的addAll()方法 4.使用Sprin ...
- C语言中调用数组元素的三种方法:下标法、数组名法、指针法
/*调用数组元素的三种方法:下标法.数组名法.指针法*/ #include<stdio.h> int main() {int a[] = { 1,2,3,4,5 }, i, * p;pri ...
最新文章
- ant Design Pro 登录状态管理
- 特斯拉2021全年交付近百万辆,同比暴涨87%,马斯克:了不起!
- indy10 UDP实例
- 云现场 | 为什么说边缘计算是5G时代的必备品?
- 终于修好了MacBook
- Python查找算法之 -- 列表查找和二分查找
- python俄罗斯方块代码34行_Python:游戏:300行代码实现俄罗斯方块
- 数据仓库分层设计,零基础一看就会
- qemu-img命令详解
- 九大内置对象及四大类
- QMC解码-某音乐解码
- 日语N2听力常用词汇
- DescendingOrder
- 《麦田里的守望者》感
- P3 元宝第三天的笔记
- 细究Android开发代码中心化所带来的问题
- android 系统中的时区设置
- 软件开发随笔系列一——分布式架构实现
- 国科大《自然语言处理》复习(宗成庆老师)
- LRUCache的C++实现
热门文章
- mysql uuid_short 为什么不存在_MySQL内置函数uuid和uuid_short
- java maven mainclass_使用Maven运行Java main的3种方式
- linux tcp参数调优,Linux TCP 性能调优笔记
- python爬虫京东中文乱码_python3爬虫中文乱码之请求头‘Accept-Encoding’:br 的问题...
- mysql取最大一条数据,mysql取出表中,某字段值最大的一条纪录,sql语句
- 字符串格式化成时间格式_小程序wxs中的时间格式化以及格式化时间和date时间互转...
- 清华等高校自评称“已建成世界一流大学”?教育部回应
- 值得一看的PCB接地设计规范!
- 一文带你认识FPGA~
- 【第二期】那些设计漂亮、有创意的电路板!