C # XML serialization method and common characteristics Summary Analysis _c# Tutorial

Source: Internet
Author: User
Tags comparison table exception handling serialization static class xmlns

This article summarizes the C # XML serialization method and common characteristics. Share to everyone for your reference, specific as follows:

C # Object XML Serialization (i): Serialization methods and common features

The. Net Framework provides the corresponding System.Xml.Seriazliation.XmlSerializer responsible for serializing objects to XML and deserializing them from XML to objects. The use of serializer is more intuitive, the need to pay more attention to the XML serialization related attribute, how to apply these attributes to our objects, as well as the object of public properties above, to generate the expected format of XML.

Here is a list of the most common methods and features, covering most of the day-to-day conversion work, and I hope you'll be quick in your work. In order to give you an intuitive impression, here give a specific use of code, in order to save space, code exception handling has not been added, when you use the appropriate Add.

1. Serializer method

The following method encapsulates the XmlSerializer invocation, which lists the most complete version of the parameter, with the appropriate addition of overloads when used:

public static class XmlSerializer {public static void SaveToXML (String FilePath, Object sourceobj, type type, String x Mlrootname) {if (!string).
      Isnullorwhitespace (FilePath) && sourceobj!= null) {type = Type!= null? Type:sourceObj.GetType (); using (StreamWriter writer = new StreamWriter (FilePath)) {System.Xml.Serialization.XmlSerializer Xmlse Rializer = string.
          Isnullorwhitespace (xmlrootname)? New System.Xml.Serialization.XmlSerializer (type): New System.Xml.Serialization.XmlSerializer (Type, new Xmlroota
        Ttribute (Xmlrootname));
      Xmlserializer.serialize (writer, sourceobj);
    }} public static object LoadFromXML (string filePath, type type) {object result = NULL; if (file.exists (FilePath)) {using (StreamReader reader = new StreamReader (FilePath)) {System.Xml .
        Serialization.xmlserializer XmlSerializer = new System.Xml.Serialization.XmlSerializer (type); ReSult = xmlserializer.deserialize (reader);
  } return result;

 }
}

2. Serialization of commonly used attribute explanation:

[XmlRootAttribute ("Mycity", namespace= "Abc.abc", Isnullable=false)]   This is the root node name when the class is an XML root node. public class city
[XmlAttribute ("AreaName")]  behaves as an XML node property. ..... Areaname= "..."/> public
string Name
[XmlElementAttribute ("Areaid", isnullable = False)]  //represented as an XML node. <AreaId>...</AreaId> public
string Id
[XmlArrayAttribute ("Areas")]  //represented as an XML hierarchy, The root is areas, and each of the collection node elements it belongs to is named the class name. <areas><area .../><area .../></areas> public
area[] Areas
[XmlElementAttribute (" Area ", isnullable = False)]  //XML node that behaves as a horizontal structure. <area .../><area .../>
. Public area[] Areas
[XmlIgnoreAttribute]  //ignores serialization of this element.

3. Detailed illustrations

Here are examples of simple cities, areas and neighborhoods to illustrate the rules.

[XmlRootAttribute ("mycity", Namespace = "Abc.abc", isnullable = False)]
public class city
{
  [XmlAttribute (' CityName ')] public
  string Name
  {get
    ;
    Set;
  }
  [XmlAttribute ("Cityid")]
  public string Id
  {get
    ;
    Set;
  }
  [XmlArrayAttribute ("Areas")]
  Public area[] Areas
  {get
    ;
    Set;
  }
}
[XmlRootAttribute ("Myarea")]
public class area
{
  [XmlAttribute (' AreaName ')] public
  string Name
  {get
    ;
    Set;
  }
  [XmlElementAttribute ("Areaid", isnullable = False)]
  public string Id
  {get
    ;
    Set;
  }
  [XmlElementAttribute ("street", IsNullable = False)]
  Public string[] Streets
  {get
    ;
    Set;
  }
}

Depending on the type above, we mock some data and then output the Util method given in step 1:

static void Main (string[] args)
{area
  area1 = new Area ();
  Area1. Name = "Pudong";
  Area1. Id = "PD001";
  Area1. Streets = new String [] {"Street 001", "Street 002"};
  Area area2 = new Area ();
  Area2. Name = "Xuhui";
  Area2. Id = "XH002";
  Area2. Streets = new String [] {"Street 003", "Street 004"};
  City city1 = new City ();
  City1. Name = "Shanghai";
  City1. Id = "SH001";
  City1. Areas = new area[] {area1, area2};
  Xmlserializer.savetoxml (@ "C:\temp\XML\output003.xml", city1);
}

The XML for the final output is:

<?xml version= "1.0" encoding= "Utf-8"?> <mycity xmlns:xsi=
"Http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd= "Http://www.w3.org/2001/XMLSchema"
Cityname= "Shanghai" cityid= "SH001" xmlns= "ABC.ABC" >
 <Areas>
  <area areaname= "Pudong" >
   <AreaId>PD001</AreaId>
   <street>street 001</street>
   <street>street 002</ street>
  </Area>
  <area areaname= "Xuhui" >
   <AreaId>XH002</AreaId>
   <street>street 003</street>
   <street>street 004</street>
  </Area>
 </Areas>
</MyCity>

Here we begin with a detailed analysis of the results, which contain some useful conclusions and considerations:

1. xml version, encoding, and namespace xmlns:xsi,xmlns:xsd are automatically added to the framework.
2. Because we use the city object as the root node, the root node name is the "mycity" we define.
But, look! This refers to the city itself as a direct root node, if the city set such as city[], at this time, the name is invalidated, the system will automatically generate the name arrayofcity as the root node name (arrayof+ class name), or we manually specify the name, This is the function of the parameter Xmlrootname in the SaveToXML () method for everyone.
3. If the city is the root node and given a name in the XmlRootAttribute attribute, and the xmlrootname is manually specified, the system will be named manually.
4. Areaname,areaid, the common property of the area class, one is interpreted as a property and one is interpreted as a child node.
The areas set is interpreted as a hierarchy, and the streets set is interpreted as a horizontal structure.
These two sets of distinctions best reflect the use of different serialization attributes.

PS: Small make up here again for everyone to recommend some of the online tools on XML operations for free use. Believe in future development can be used to:

Online XML format/compression tools:
Http://tools.jb51.net/code/xmlformat

Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson

XML code online formatting landscaping tools:
Http://tools.jb51.net/code/xmlcodeformat

Html/xml Escape character Comparison table:
Http://tools.jb51.net/table/html_escape

Read more about C # Interested readers can view the site topics: "C # XML file Operation Tips Summary", "C # Common control usage Tutorial", "WinForm Control Usage Summary", "C # Data structure and algorithm tutorial", "C # object-oriented Program design Introductory Course" and "C # A summary of thread usage tips for programming

I hope this article will help you with C # programming.

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.