This article summarizes the C# XML serialization method and common features. Share it for your reference, as follows:
C# object XML serialization (I): serialization methods and common features
.Net Framework provides corresponding responsible for serializing objects to XML and deserializing them from XML into objects. The use of Serializer is more intuitive. Pay more attention to the attributes related to XML serialization. How to apply these attributes to our objects and the public attributes of the object to generate XML that meets the expected format.
Here are the most commonly used methods and features, covering most daily conversion work. I hope everyone can get started quickly at work. In order to give everyone an intuitive impression, the specific usage code is given here. In order to save space, the code exception handling has not been added. Students will add it as appropriate when using it.
1. Serializer method
The following method encapsulates the call of XmlSerializer. Here is a version with the most complete parameters. Reloading is required when using it:
public static class XmlSerializer { public static void SaveToXml(string filePath, object sourceObj, Type type, string xmlRootName) { if (!(filePath) && sourceObj != null) { type = type != null ? type : (); using (StreamWriter writer = new StreamWriter(filePath)) { xmlSerializer = (xmlRootName) ? new (type) : new (type, new XmlRootAttribute(xmlRootName)); (writer, sourceObj); } } } public static object LoadFromXml(string filePath, Type type) { object result = null; if ((filePath)) { using (StreamReader reader = new StreamReader(filePath)) { xmlSerializer = new (type); result = (reader); } } return result; } }
2. Explanation of commonly used Attributes for serialization:
[XmlRootAttribute("MyCity", Namespace="", IsNullable=false)] // When this class is an Xml root node, use this as the root node name.public class City [XmlAttribute("AreaName")] // It is represented as an Xml node attribute. <... AreaName="..."/>public string Name [XmlElementAttribute("AreaId", IsNullable = false)] // It is represented as an Xml node. <AreaId>...</AreaId>public string Id [XmlArrayAttribute("Areas")] // It is represented as an Xml hierarchy, with the root of Areas, and each node element of the collection it belongs to is the class name. <Areas><Area ... /><Area ... /></Areas>public Area[] Areas [XmlElementAttribute("Area", IsNullable = false)] // represents an Xml node with a horizontal structure. <Area ... /><Area ... />...public Area[] Areas [XmlIgnoreAttribute] // Ignore the serialization of this element.
3. Give detailed examples
Here we use simple cities, areas and neighborhoods as examples to demonstrate the above rules in detail.
[XmlRootAttribute("MyCity", Namespace = "", 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; } }
Based on the above type, we mock some data and then output it using the Util method given in step 1:
static void Main(string[] args) { Area area1 = new Area(); = "Pudong"; = "PD001"; = new string [] { "street 001", "street 002" }; Area area2 = new Area(); = "Xuhui"; = "XH002"; = new string [] { "street 003", "street 004" }; City city1 = new City(); = "Shanghai"; = "SH001"; = new Area[] { area1, area2 }; (@"C:\temp\XML\", city1); }
The final output XML is:
<?xml version="1.0" encoding="utf-8"?> <MyCity xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:xsd="http:///2001/XMLSchema" CityName="Shanghai" CityId="SH001" xmlns=""> <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 start analyzing the results in detail, including some very useful onesConclusions and precautions:
1. The 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 defined.
But, be careful! This refers to using City itself as the root node directly. If it is a City collection such as City[], at this time, the name is invalid. 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 City is the root node and the name is given in the XmlRootAttribute attribute, and xmlRootName is also manually specified, the system will use the manually specified name.
4. AreaName, AreaId, are both public attributes of the Area class, one is interpreted as an attribute and the other is interpreted as a child node.
Areas sets are interpreted as hierarchical structures, and Streets sets are interpreted as horizontal structures.
These two sets of differences best reflect the usage of different serialized Attributes.
PS: Here I will recommend a few online tools for everyone to use for free. I believe that it can be used in future development:
Online XML formatting/compression tools:
http://tools./code/xmlformat
Online XML/JSON mutual conversion tool:
http://tools./code/xmljson
XML code online formatting and beautification tool:
http://tools./code/xmlcodeformat
HTML/XML escape character comparison table:
http://tools./table/html_escape
For more information about C# related content, please check out the topic of this site:Summary of XML file operation skills in C#》、《Tutorial on the usage of common C# controls》、《Summary of WinForm control usage》、《C# data structure and algorithm tutorial》、《Introduction to C# object-oriented programming tutorial"and"Summary of thread usage techniques for C# programming》
I hope this article will be helpful to everyone's C# programming.