XML serialization and deserialization

Source: Internet
Author: User

Before we talk about XML serialization, let's first say serialization.


Serialization noun Interpretation: serialization is the process of converting an object's state into a format that can be persisted or transmitted.


Relative to serialization is deserialization, which transforms a stream into an object. Together, these two processes make it easy to store and transfer data. This is where serialization is meant to be.

We can serialize objects into different formats, such as JSON serialization, XML serialization, binary serialization, SOAP serialization, and so on, all of which are designed to accommodate specific business requirements.

In this article, we analyze the serialization and deserialization of XML. Let's look at an XML file first:

<?xml version= "1.0"  encoding= "Utf-8"  ?><BaseInfo>  <Person>     <Name> Xiao Ming </Name>    <Age>16</Age>     <Books>      <Book>         <ISBN>123</ISBN>        <Title> borrowed the book 1</ title>      </book>    </books>   </Person>  <Person>    <Name> Little Red </Name>     <Age>18</Age>    <Books>      < book>        <isbn>456</isbn>         <Title> borrowed the book 2</title>      </book>       <book>        <isbn>789</isbn>         <Title> borrowed the book 3</title>      </ Book>    </books>  </person></baseinfo>

In this file baseinfo for the XML node, which consists of a plurality of person nodes, in the person node also includes name, age, books node, books node is composed of multiple book, in the book also includes ISBN and title.


The first thing we do here is to create the object corresponding to the XML, then convert the object to the XML described above (serialization), or convert the XML to an object (deserialization). In the following example, just save the XML locally, read it locally, and if it needs to be transferred over the network, add the serializable attribute, and we'll start by creating the object.

Using System.xml.serialization;public class baseinfo{list<person> perlist = new list<person> ();       [XmlElement (elementname= "person")] public list<person> perlist {get {return perlist;}    set {perlist = value;} }}

Using XML serialization requires the introduction of namespace System.Xml.Serialization. The class name we created is Baseinfo, which corresponds to the XML node, and of course we can also specify the name that is mapped when the class is converted to XML, where you can use elementname in XmlRoot to specify its name. Just like the attribute perlist in this class, you can also use the easier way that the name of the class is the same as the name of the XML node, as in the example. In the Baseinfo class, we maintain a perlist that is a collection of person objects, and of course the name of this property does not correspond to the XML file, so change its name to person.


OK, let's look at the person class:

using system.xml.serialization;public class person{     string  name;     int age;     list<books> booklist= New list<books> ();      /// <summary>      ///  must have a default constructor      /// </summary>      public person ()      { }      public  person (string name, int age)      {          this.name = name;          This.age = age;     }      public string  name     {         get {  return name; }         set { name = value; }      }      public int Age      {         get { return age; }          set { age = value; }      }      [xmlelement (elementname =  "Books")]      public List<Books> BookList     {          get { return bookList; }          set { bookList = value; }      } }

There is name and age in the class, and a books object is maintained.


Let's look at books again:

Using System.xml.serialization;public class books{list<book> Booklist = new list<book> ();        [XmlElement (elementname = "book")] public list<book> Booklist {get {return booklist;}    set {Booklist = value;} }}

The function of books is like a transitional class that maintains a collection of objects for the book class in this class only to correspond to the nodes books in the XML.


So, finally, let's look at the book class:

using system.xml.serialization;public class book{    string isbn;     string title;     public book ()  { }      public book (String isbn, string title)     {         this.isbn = isbn;         this.title = title;    }     public  string isbn    {        get {  return isbn; }        set { isbn =  value; }    }      public string title     {        get { return title;  }        set { title = value; }    }   } 

OK, so that the classes we need are all created, although the process of creating classes is a bit cumbersome, but with these classes, we do not have a node to process XML. We create a simple console program that adds two processing methods, the first of which is a serialization method:

Public static void xmlserialize () {    book b1 = new  Book ("111", "Books 1"),     book b2 = new book ("222", "Book 2");     book b3 = new book ("333", "Book 3");    books bs1 =  New books ();     books bs2 = new books ();     BS1. Booklist.add (B1);     bs1. Booklist.add (B2);     bs2. Booklist.add (b3);     person p1 = new person ("Zhang San",  11);     person p2 = new person ("John Doe",  22);     p1. Booklist.add (BS1);     p2. Booklist.add (BS2);     baseinfo baseinfo = new baseinfo ();     baseinfo.perlist.add (p1);     baseinfo.perlist.add (p2);     stringwriter sw = new stringwriter ();     //Creating XML Namespaces      xmlserializernamespaces ns = new xmlserializernamespaces ();     ns. Add ("", "");     xmlserializer serializer = new xmlserializer (typeof ( Baseinfo));     serializer. Serialize (Sw, baseinfo, ns);     sw. Close ();      console.write (SW. ToString ());}

Call this method to run the effect:


The second is a deserialization method:

Public static void xmldeserialize () {    //xml Source may be an external file, or it may be obtained from another system      filestream file = new filestream (@ "Http://www.cnblogs.com/info.xml",  filemode.open, fileaccess.read);     xmlserializer xmlsearializer =  new xmlserializer (typeof (Baseinfo));    baseinfo info =  ( Baseinfo) xmlsearializer.deserialize (file);     file. Close ();    foreach  (person per in info. perlist)     {        console.writeline ("Personnel:");         console.writeline ("  Name:"  + per. Name);         console.writeline ("  Age:"  + per. Age);        foreach  (books b1 in per. Booklist)    &Nbsp;    {            foreach   (BOOK&NBSP;B&NBSP;IN&NBSP;B1. Booklist)             {                 console.writeline ("  Book:");                 console.writeline (" &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;ISBN: "&NBSP;+&NBSP;B.ISBN);                 console.writeline ("      title:"  +  b.title);            }         }    }}

Call this method to run the effect:

XML serialization and deserialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.