Summary and analysis of C XML serialization method and common characteristics

  • 2021-10-16 02:29:15
  • OfStack

This article summarizes the C # XML serialization methods and common features with examples. Share it for your reference, as follows:

C # Object XML Serialization (1): Serialization Methods and Common Features

Net Framework provides the corresponding System. Xml. Seriazliation. XmlSerializer for serializing objects to XML and deserializing objects from XML. The use of Serializer is intuitive. More attention should be paid to XML serialization related Attribute. How to apply these attribute to our objects and the public attributes of objects to generate XML that meets the expected format.

Here are the most commonly used methods and features, covering most of the daily conversion work. I hope everyone can get started quickly in the work. In order to give you an intuitive impression, the specific use of code is given here. In order to save space, the code exception handling has not been added, and you can add it as appropriate when you use it.

1. Serializer method

The following method encapsulates the call of XmlSerializer, and the most complete version of parameters is listed here. When using it, it is necessary to add overload appropriately:


public static class XmlSerializer
{
  public static void SaveToXml(string filePath, object sourceObj, Type type, string xmlRootName)
  {
    if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
    {
      type = type != null ? type : sourceObj.GetType();
      using (StreamWriter writer = new StreamWriter(filePath))
      {
        System.Xml.Serialization.XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
          new System.Xml.Serialization.XmlSerializer(type) :
          new System.Xml.Serialization.XmlSerializer(type, new XmlRootAttribute(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 instructions:


[XmlRootAttribute("MyCity", Namespace="abc.abc", IsNullable=false)]   //  When the class is Xml Root node, this is the root node name. 
public class City
[XmlAttribute("AreaName")]  //  Manifested as Xml Node properties. <... AreaName="..."/>
public string Name
[XmlElementAttribute("AreaId", IsNullable = false)]  //  Manifested as Xml Node. <AreaId>...</AreaId>
public string Id
[XmlArrayAttribute("Areas")]  //  Manifested as Xml Hierarchy with root of Areas Each of the collection node elements to which it belongs is named a class name. <Areas><Area ... /><Area ... /></Areas>
public Area[] Areas
[XmlElementAttribute("Area", IsNullable = false)]  //  Showing a horizontal structure Xml Node. <Area ... /><Area ... />...
public Area[] Areas
[XmlIgnoreAttribute]  //  Ignore the serialization of the element. 

3. Detailed examples

Here, use simple cities, regions and blocks as examples to demonstrate the above rules in detail.


[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;
  }
}

According to the above types, we mock1 some data, and then output it using 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 final output XML 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>

Let's begin to analyze the results in detail, which contains one useful conclusion and precautions:

1. xml version, encoding, and namespaces xmlns: xsi, xmlns: xsd are automatically added for Framework.
2. Because we use the City object as the root node, the root node name is our defined "MyCity".
But, pay attention! This refers to using City itself as the root node directly. If it is an City collection such as City [], at this time, the name is invalid, and the system will automatically generate the name ArrayOfCity as the root node name (ArrayOf + class name), or we can specify the name manually. This is the role of the parameter xmlRootName in the SaveToXml () method for everyone.
3. If City is the root node and the name is given in the XmlRootAttribute attribute, and xmlRootName is also manually specified, the name specified manually will prevail.
4. AreaName and AreaId are common attributes of Area class, one is interpreted as an attribute and the other is interpreted as a child node.
The Areas set is interpreted as a hierarchical structure, and the Streets set is interpreted as a horizontal structure.
These two sets of differences best reflect the usage of different serialized Attribute.

PS: Here we recommend several online tools for xml operation for free use. I believe it can be used in future development:

Online XML Formatting/Compression Tool:
http://tools.ofstack.com/code/xmlformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

xml code online formatting beautification tool:
http://tools.ofstack.com/code/xmlcodeformat

HTML/XML Escape Character Comparison Table:
http://tools.ofstack.com/table/html_escape

For more readers interested in C # related content, please check the topics on this site: "Summary of XML File Operation Skills in C #", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Data Structure and Algorithm Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "C # Programming Thread Use Skills Summary"

I hope this article is helpful to everyone's C # programming.


Related articles: