C # object XML serialization (1): serialization methods and Common Features

Source: Internet
Author: User

. NET Framework provides the corresponding system. xml. seriazliation. xmlserializer to serialize objects to XML and deserialize objects from XML. Serializer is more intuitive to use. pay more attention to the XML serialization-related attributes. How can we apply these attributes to our objects and the object's public attributes, generate XML that meets the expected format.
This article lists the most common methods and features, covering most of the daily conversion work. I hope you can get started quickly at work. To give you an intuitive impression, the specific code is provided here. To save space, code exception handling is not added. You can add code when using it as appropriate.

1. Serializer Method

The following method encapsulates the call of xmlserializer. The most complete version of the parameter is listed here. You need to add a reload when using it:

    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. Explanation of common serialization attributes:

[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")] // shows the 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")] // shows the XML hierarchy. The root is areas, and each node element of the set to which it belongs is named the class name. <Areas> <area.../> </areas>
Public Area [] Areas

[Xmlelementattribute ("area", isnullable = false)] // shows XML nodes in a horizontal structure. <Area.../>...
Public Area [] Areas

[Xmlignoreattribute] // ignore serialization of this element.

 

3. Examples

Here we use simple cities, regions, and blocks as examples to illustrate the above 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;
}
}

Based on the above data types, we use the util method given in step 1 to output some mock data:

    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>

The following describes the specific analysis results, including some useful conclusions and precautions:
1.The XML version, encoding, and namespace xmlns: xsi, xmlns: XSD are automatically added for the framework.

2.Because the city object is used as the root node, the root node name is "mycity ".
But note! Here, the city itself is used as the root node. If it is a city set such as city [], the name is invalid, the system will automatically generate the name arrayofcity as the root node name (arrayof + class name), or manually specify the name. This is the role of the xmlrootname parameter in the savetoxml () method for everyone.

3.If the City node is used as the root node and the name is specified in the XmlRootAttribute attribute, and the xmlRootName is also manually specified, the system determines the name manually specified.

4.AreaName and AreaId are common attributes of the Area class. One is interpreted as an attribute and the other is interpreted as a subnode.
The Areas set is interpreted as a hierarchy, and the Streets set is interpreted as a horizontal structure.
These two sets of differences best reflect the usage of different serialization attributes.

4. Conclusion
Here we use an example to illustrate the usage of Xml Serializer. The structure ing between C # class and Xml is expected to be enough for the students to deal with daily work. More in-depth discussions will be followed up in subsequent articles.

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.