[. Net Object-Oriented programming advanced] (10) Serialization (Serialization) (2) Learn XML Serialization through Serialization of blog garden articles, blog Garden

Source: Internet
Author: User

[. Net Object-Oriented programming advanced] (10) Serialization (Serialization) (2) Learn XML Serialization through Serialization of blog garden articles, blog Garden

[. Net Object-Oriented programming advanced] (10) Serialization (Serialization) (2) Learning XML Serialization through Serialization blog garden articles

This section introduces:

In the previous section, we introduced the serialization of binary streams. In this section, we will continue to introduce XML serialization and deserialization. XML, as the W3C standard data transmission format, is essential for. NET Object-Oriented Programming to understand and use the XML serialization class XmlSerializer.

Before reading:

A. modifier [. net connector Object-Oriented Programming Basics] modifier (8) Modifier

B. Examples of classes and classes [. net idea Object-Oriented Programming Basics] example (9) Examples of classes and Classes

C. Member of the class [. net Framework Object-Oriented Programming Basics] member of the category (10) Member of the category (field, attribute, method)

D. array and set [. net idea Object-Oriented Programming Basics] objective functions (17) array and set

E. Generic [. net idea Object-Oriented Programming Basics] generic programming (18) Generic

F. LINQ use [. net idea Object-Oriented Programming Basics] (20) Use

1. About XML

XML refers to the EXtensible Markup Language (EXtensible Markup Language)

XML is a markup language, similar to HTML

XML is designed to transmit data rather than display data.

The XML tag is not predefined. You need to customize the tag.

XML is designed to be self-descriptive.

XML is W3C recommendation Standard

The basic knowledge about XML is not detailed here.

2. XML serialization

The namespace for XML Serialization is: System. Xml. Serialization.

Class: XmlSerializer

Main Methods: Serialize and Deserialize

Next, let's take a look at a simple and interesting XML serialization. In order to make friends interested in reading it, I will dynamically obtain the real-time data of the blog site (this is not the focus, this section focuses on serialization and deserialization.

First, obtain the blog post and create the article entity class as follows:

public class MyBlogs
{
    /// <summary>
    /// Get articles from my blog garden
    /// </ summary>
    /// <returns> </ returns>
    public static List <MyArticle> GetMyArticle (int count)
    {
        var document = XDocument.Load (
            "http://wcf.open.cnblogs.com/blog/u/yubinfeng/posts/1/" + count
            );
        List <MyArticle> myArticleList = new List <MyArticle> ();
        var elements = document.Root.Elements ();

        // Before doing this work, let's get the list of articles in my blog
        var result = elements.Where (m => m.Name.LocalName == "entry"). Select (myArticle => new MyArticle
        {
            id = Convert.ToInt32 (myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "id"). Value),
            title = myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "title"). Value,
            published = Convert.ToDateTime (myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "published"). Value),
            updated = Convert.ToDateTime (myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "updated"). Value),
            diggs = Convert.ToInt32 (myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "diggs"). Value),
            views = Convert.ToInt32 (myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "views"). Value),
            comments = Convert.ToInt32 (myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "comments"). Value),
            summary = myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "summary"). Value,
            link = myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "link"). Attribute ("href"). Value,
            author = myArticle.Elements (). SingleOrDefault (x => x.Name.LocalName == "author"). Elements (). SingleOrDefault (x => x.Name.LocalName == "name"). Value
        }). OrderByDescending (m => m.published);
        myArticleList.AddRange (result);
        return myArticleList;
    }
}
/// <summary
/// My blog post entity class
/// </ summary>

public class MyArticle
{
    /// <summary>
    /// Article ID
    /// </ summary>
    public int id {get; set;}
    /// <summary>
    /// article title
    /// </ summary>
    public string title {get; set;}
    /// <summary>
    /// Thesis
    /// </ summary>
    public string summary {get; set;}
    /// <summary>
    /// release time
    /// </ summary>
    public DateTime published {get; set;}
    /// <summary>
    /// Last update time
    /// </ summary>
    public DateTime updated {get; set;}
    /// <summary>
    /// URL address
    /// </ summary>
    public string link {get; set;}
    /// <summary>
    /// number of recommendations
    /// </ summary>
    public int diggs {get; set;}
    /// <summary>
    /// views
    /// </ summary>
    public int views {get; set;}

    /// <summary>
    /// comments
    /// </ summary>
    public int comments {get; set;}
    /// <summary>
    /// Author
    /// </ summary>
    public string author {get; set;}
}

The following describes how to serialize the XML Object of myArticleList and output it to the console.

// XML serialization namespace: System.Xml.Serialization;
// Class: XmlSerializer
// Main method: Serialize and Deserialize

// Objection (deserialization) and serialization of blog data

// (1) Get the last 10 articles in my blog garden (actually this process is also deserialization)
List <MyArticle> myArticleList = MyBlogs.GetMyArticle (10);
// (2) serialize the above object myArticleList to XML and output to the console
string xmlString = String.Empty;
using (MemoryStream ms = new MemoryStream ())
{
               
     XmlSerializer xml = new XmlSerializer (typeof (List <MyArticle>));
     xml.Serialize (ms, myArticleList);
     byte [] arr = ms.ToArray ();
     xmlString = Encoding.UTF8.GetString (arr, 0, arr.Length);
     ms.Close ();
}
Console.WriteLine (xmlString);

The running result is as follows:

 

In the above example, the most basic serialization from object to XML is realized. Next, the xmlString Text object serialized in the preceding example is converted to List <MyArticle>

3. XML deserialization

Xml deserialization: the process of converting Xml text into objects.

We deserialize the serialized text xmlString to a List <MyArticle> object.

// The xmlString text that we just output is objectized (deserialized) into a List object
using (StringReader sr = new StringReader (xmlString))
{
     XmlSerializer xml = new XmlSerializer (typeof (List <MyArticle>));
                     ;
     List <MyArticle> myNewArticleList = xml.Deserialize (sr) as List <MyArticle>;

     // Iterate through the new objects myNewArticleList of the output order
     myNewArticleList.ForEach (m =>
         Console.WriteLine ("Article ID:" + m.id + "\ nArticle Title:" + m.title)
     );
     sr.Close ();
}

The running result is as follows:


The preceding example deserializes the XML text into a List <MyArticle> object.

After learning the two examples above, I have mastered the basic knowledge of XML serialization and deserialization. Next I will introduce some details in the serialization process.

4. Precautions for XML serialization

(1) the class to be serialized must have a default constructor to be serialized using XmlSerializer, all classes to be serialized must have a constructor without parameters. (By studying basic classes and class instances, we must know that classes do not define constructor, A non-parameter constructor is generated by default );

(2) The indexer, private field, or read-only attribute (except for the read-only set attribute) cannot be serialized;

(3) If you do not want to serialize an attribute, use [System. xml. serialization. xmlIgnore] Mark, which can be used for attributes; [NonSerializable] is used for invalid attributes, and can be used for classes and struct;

(4) methods cannot be serialized (although it is nonsense, it is still listed );

(5) Enumeration variables can be serialized as strings without the use of [XmlInclude]

(6) to export non-basic type objects, you must use [XmlInclude] to declare them in advance. This rule recursively applies to child elements.

(7) If the IsNullable parameter in Attribute is equal to false, it indicates that if the element is null, this element is not displayed. (Valid for value types)

(8) some classes cannot be serialized in XML (even if [XmlInclude] is used).

For example:

IDictionary (such as HashTable );

When the parent class object is assigned a subclass object value;

Circular reference between objects;

(9) For objects that cannot be serialized in XML, consider:

Use custom xml serialization (implementing the IXmlSerializable Interface );

For classes that implement IDictionary, consider (1) replacing it with other collection classes; (2) encapsulating it with classes and providing the Add and this functions;

Some types must be converted before being serialized into XML. For example, if the XML serialization System. Drawing. Color, you can first use ToArgb () to convert it to an integer;

If xml serialization is inconvenient for overly complex objects, binary serialization can be considered;

(10) The default constructor is required. Because deserialization uses reflection in essence, the default constructor is required to instantiate the class. If the default constructor is removed, the compilation is normal, however, an error will be reported during running.

Do not place large attributes in the default constructor initialization, which will lead to list initialization twice during deserialization: the default constructor is executed once, when deserialization is performed, it is read from the XML document and executed again.

Pay attention to the above ten points. The first three points, that is, the black points, are important to know.

5. Change the default value of XML serialization.

5.1 change or delete the default namespace of XML

Use the XmlSerializerNamespaces class (System. Xml. Serialization. XmlSerializerNamespaces ). To complete

We serialize the List <MyArticle> of the heaviest object above and change the default namespace of XML, as shown in the following example:

// Update the default namespace
// Use XmlSerializerNamespaces class to complete (System.Xml.Serialization.XmlSerializerNamespaces)
System.Xml.Serialization.XmlSerializerNamespaces XmlSN = new XmlSerializerNamespaces ();
// Get article list object
List <MyArticle> newArticleList = MyBlogs.GetMyArticle (10);
// Change the namespace and output
string newXmlString = String.Empty;
XmlSN.Add ("MyBlogURL", @ "http://www.cnblogs.com/yubinfeng");
using (MemoryStream ms = new MemoryStream ())
{
     XmlSerializer xml = new XmlSerializer (typeof (List <MyArticle>));
     xml.Serialize (ms, newArticleList, XmlSN);
     byte [] arr = ms.ToArray ();
     newXmlString = Encoding.UTF8.GetString (arr, 0, arr.Length);
     ms.Close ();
}
Console.WriteLine (newXmlString);

We can compare it with the default output result, for example:

 

You can also delete a namespace.

System.Xml.Serialization.XmlSerializerNamespaces XmlSN = new XmlSerializerNamespaces();    XmlSN.Add("","");

When an empty namespace is added, the default XML namespace can be deleted.

5.2 modify other elements of XML serialization

First, we will list the attributes that XmlWriterSettings can change.

XmlWriterSettings has the following attributes:

Member

Description

CloseOutput

Gets or sets a value that indicates whether XmlWriter should disable the base stream or TextWriter when calling the Close method.

Encoding

Gets or sets the type of text encoding to be used.

Indent

Gets or sets a value indicating whether to indent an element.

IndentChars

The string used to obtain or set indentation.

NamespaceHandling

Gets or sets a value that indicates whether XmlWriter should remove duplicate namespace declarations when writing XML content. By default, all namespace declarations appear in the output program.

NewLineChars

Gets or sets the string to be used for the branch character

NewLineHandling

Gets or sets a value indicating whether to normalize the branch character in the output.

NewLineOnAttributes

Gets or sets a value indicating whether to write the attribute to a new row.

OmitXmlDeclaration

Get or set a value to indicate that the XML declaration is omitted.

Encoding

Gets or sets the type of text encoding to be used.

Reset Method

Reset the above attributes

API official address: http://msdn.microsoft.com/zh-cn/library/system.xml.xmlwritersettings (v = vs.110). aspx

The following is an example. To set three attributes: remove the XML declaration, line feed indent, and specify the character indent, for example:

Define a method first

/// <summary>
/// Set three attributes: remove XML declaration, specify character indent
/// </ summary>
/// <param name = "Obj"> </ param>
/// <returns> </ returns>
public static string ObjectToXmlSerializer (Object Obj)
{
     System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings ();
            
     settings.OmitXmlDeclaration = true; // Remove xml declaration
     settings.Encoding = Encoding.Default; // Use the default encoding
     settings.IndentChars = "-"; // Indent using specified characters
     settings.Indent = true; // newline indent
     System.IO.MemoryStream mem = new MemoryStream ();
     using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create (mem, settings))
     {
         // Remove the default namespaces xmlns: xsd and xmlns: xsi
         XmlSerializerNamespaces ns = new XmlSerializerNamespaces ();
         ns.Add ("", "");
         XmlSerializer formatter = new XmlSerializer (Obj.GetType ());
         formatter.Serialize (writer, Obj, ns);
     }
     return Encoding.Default.GetString (mem.ToArray ());
}

The call is as follows:

// Use the properties of the XmlWriterSettings class to change other elements of the serialized XML
// The namespace: System.Xml.XmlWriterSettings
// Set three properties: remove XML declaration, specify character indent
Console.WriteLine (ObjectToXmlSerializer (myArticleList)); 

The output result is compared with the previous one, for example:

 

6. Highlights of this section:

(1) understand XML serialization and convert objects into XML data formats

(2) understand XML deserialization and convert XML text into objects

(3) Pay attention to the considerations for XML order change. The main points are as follows:

  • Default class and non-parameter constructor class can be serialized;
  • The indexer, private field, or read-only attribute (except the read-only set attribute) cannot be serialized.
  • Some serialized tags use the [System. Xml. Serialization. XmlIgnore] tag when you do not want to serialize an attribute, which can be used for attributes;
  • [NonSerializable] the attribute is invalid and can be used for classes and struct.

(4) change the default value of XML serialization:

Use the XmlSerializerNamespaces class (System. Xml. Serialization. XmlSerializerNamespaces) to change or delete the XML namespace;

Use the attributes of the XmlWriterSettings class (System. Xml. XmlWriterSettings) to change the clear name, indentation, and other elements of XML. 

In the next section, we will introduce XML serialization and introduce other features of XML by implementing the serialization interface IXmlSerializable, and give an example to illustrate the advanced application of XML serialization.


Related Article

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.