C# 中xml数组的序列和反序列化方法
先來(lái)看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>高等數(shù)學(xué)</Title><ISBN>SOD1S8374</ISBN></Book></Books></Person><Person><Name>小紅</Name><Age>20</Age><Books><Book><Title>思想</Title><ISBN>SID1323D845</ISBN></Book></Books></Person> </root>?
這個(gè)xml包含多個(gè)Person對(duì)象,每個(gè)Person對(duì)象又包含一個(gè)Books對(duì)象和多個(gè)book對(duì)象,反序列化XML時(shí)關(guān)鍵是看怎么理解xml的結(jié)構(gòu),理解正確了就很好構(gòu)造對(duì)應(yīng)的類,理解錯(cuò)了可能就陷入坑里。
首先root是整個(gè)文件的根節(jié)點(diǎn),它是由多個(gè)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對(duì)象,Person是由name和age兩個(gè)屬性和一個(gè)Books對(duì)象組成,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; }}這里理解的關(guān)鍵是把下面這小段xml理解成一個(gè)包含多個(gè)Book的對(duì)象,而不是把它理解成book的數(shù)組
<Books><Book><Title>毛澤思想</Title><ISBN>SID1323DSD</ISBN></Book></Books>如果把她理解成一個(gè)數(shù)據(jù)就容易把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節(jié)點(diǎn)
,生成的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>?
之所以出現(xiàn)上面的情況是因?yàn)?#xff1a;
public List<Book> Books { get; set; } 和Book同屬一個(gè)節(jié)點(diǎn)層次,在List<Book> Books上顯式指定了屬性名稱Books,那么這個(gè)節(jié)點(diǎn)就是Books,跟Book上定義指定的[System.Xml.Serialization.XmlRootAttribute("Book", IsNullable = false)] 沒(méi)有關(guān)系,它是用來(lái)指示Book是跟節(jié)點(diǎn)時(shí)的名稱。 或者可以這樣理解xml是由多個(gè)節(jié)點(diǎn)組成的,而B(niǎo)ook類定義不是一個(gè)節(jié)點(diǎn),它只是一個(gè)定義,要想xml中出現(xiàn)book,就需要再加一個(gè)節(jié)點(diǎn),我們把Person節(jié)點(diǎn)加到Books對(duì)象中 [System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]public class Books{[System.Xml.Serialization.XmlElementAttribute("Book")]public List<Book> BookList { get; set; }}這樣就多出了一個(gè)節(jié)點(diǎn),再結(jié)合剛開(kāi)始的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("對(duì)象序列化成xml時(shí)發(fā)生錯(cuò)誤:" + ex.Message);}return result;}/// <summary>/// 序列化XML時(shí)不帶默認(rèn)的命名空間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("對(duì)象序列化成xml時(shí)發(fā)生錯(cuò)誤:" + ex.Message);}return result;}/// <summary>/// 序列化時(shí)不生成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("對(duì)象序列化成xml時(shí)發(fā)生錯(cuò)誤:" + 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轉(zhuǎn)換成對(duì)象時(shí)發(fā)生錯(cuò)誤:" + ex.Message);}return root;}} } 再看一個(gè)例子,簡(jiǎn)單數(shù)組類型的序列化 <?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>我們經(jīng)常搞半天不知道要怎么書寫上面xml對(duì)應(yīng)的類,總是容易出現(xiàn)上面說(shuō)過(guò)的錯(cuò)誤,關(guān)鍵還是看怎么理解barcodes,和上面的例子類似,這里只寫類怎么創(chuàng)建
[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); } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的C# 中xml数组的序列和反序列化方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Linux 下压缩与解压.zip 和 .
- 下一篇: 解决:Throwable:Stub in