SoFunction
Updated on 2025-03-06

How to convert entity classes and XML in C#

1. Entity class and XML are converted

Converting entity classes to XML requires the use of the Serialize method of the XmlSerializer class to serialize the entity classes.

To convert XML into the corresponding entity class, you need to use the Deserialize method of the XmlSerializer class to deserialize the XML.

Create XML serialization public processing class ()

using System;
using ;
using ;
/// <summary>
/// XML serialization public processing class/// </summary>
public static class XmlSerializeHelper
{
    /// <summary>
    /// Convert entity objects to XML    /// </summary>
    /// <typeparam name="T">Entity type</typeparam>    /// <param name="obj">Entity Object</param>    public static string XmlSerialize&lt;T&gt;(T obj)
    {
        try
        {
            using (StringWriter sw = new StringWriter())
            {
                Type t = ();
                XmlSerializer serializer = new XmlSerializer(());
                (sw, obj);
                ();
                return ();
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Convert entity objects to XML exception", ex);
        }
    }
    /// &lt;summary&gt;
    /// Convert XML to entity object    /// &lt;/summary&gt;
    /// <typeparam name="T">Entity type</typeparam>    /// &lt;param name="strXML"&gt;XML&lt;/param&gt;
    public static T DESerializer&lt;T&gt;(string strXML) where T : class
    {
        try
        {
            using (StringReader sr = new StringReader(strXML))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return (sr) as T;
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Convert XML to entity object exception", ex);
        }
    }
}

Create a user information class for example use.

/// &lt;summary&gt;
/// User information category/// &lt;/summary&gt;
public class UserInfo
{
    /// &lt;summary&gt;
    /// serial number    /// &lt;/summary&gt;
    public int ID { get; set; }
    /// &lt;summary&gt;
    /// Name    /// &lt;/summary&gt;
    public string Name { get; set; }
    /// &lt;summary&gt;
    /// Creation time    /// &lt;/summary&gt;
    public DateTime? CreateTime { get; set; }
}

1.1 Example 1: Convert List and XML to each other

/// &lt;summary&gt;
/// Convert List and XML to each other/// &lt;/summary&gt;
public static void ListToXmlTest()
{
    //Get user list    List&lt;UserInfo&gt; userList = GetUserList();
    //Convert entity objects to XML    string xmlResult = (userList);
    //Convert XML to entity object    List&lt;UserInfo&gt; deResult = &lt;List&lt;UserInfo&gt;&gt;(xmlResult);
}
/// &lt;summary&gt;
/// Get a list of user information/// &lt;/summary&gt;
public static List&lt;UserInfo&gt; GetUserList()
{
    List&lt;UserInfo&gt; userList = new List&lt;UserInfo&gt;();
    (new UserInfo() { ID = 1, Name = "Zhang San", CreateTime =  });
    (new UserInfo() { ID = 2, Name = "Li Si", CreateTime =  });
    (new UserInfo() { ID = 2, Name = "Wang Wu" });
    return userList;
}

XML results:

&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;ArrayOfUserInfo xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:xsd="http:///2001/XMLSchema"&gt;
  &lt;UserInfo&gt;
    &lt;ID&gt;1&lt;/ID&gt;
    &lt;Name&gt;Zhang San&lt;/Name&gt;
    &lt;CreateTime&gt;2018-10-04T15:59:53.7761027+08:00&lt;/CreateTime&gt;
  &lt;/UserInfo&gt;
  &lt;UserInfo&gt;
    &lt;ID&gt;2&lt;/ID&gt;
    &lt;Name&gt;Li Si&lt;/Name&gt;
    &lt;CreateTime&gt;2018-10-04T15:59:54.9571044+08:00&lt;/CreateTime&gt;
  &lt;/UserInfo&gt;
  &lt;UserInfo&gt;
    &lt;ID&gt;2&lt;/ID&gt;
    &lt;Name&gt;Wang Wu&lt;/Name&gt;
    &lt;CreateTime xsi:nil="true" /&gt;
  &lt;/UserInfo&gt;
&lt;/ArrayOfUserInfo&gt;

1.2 Example 2: Convert DataTable and XML to each other

/// &lt;summary&gt;
/// Convert DataTable and XML to each other/// &lt;/summary&gt;
public static void DataTableToXmlTest()
{
    //Create DataTable object    DataTable dt = CreateDataTable();
    //Convert DataTable to XML    string xmlResult = (dt);
    //Convert XML to DataTable    DataTable deResult = &lt;DataTable&gt;(xmlResult);
}
/// &lt;summary&gt;
/// Create DataTable object/// &lt;/summary&gt;
public static DataTable CreateDataTable()
{
    //Create DataTable    DataTable dt = new DataTable("NewDt");
    //Create a self-growing ID column    DataColumn dc = ("ID", ("System.Int32"));
    (new DataColumn("Name", ("")));
    (new DataColumn("CreateTime", ("")));
    //Create data    DataRow dr = ();
    dr["ID"] = 1;
    dr["Name"] = "Zhang San";
    dr["CreateTime"] = ;
    (dr);
    dr = ();
    dr["ID"] = 2;
    dr["Name"] = "Li Si";
    dr["CreateTime"] = ;
    (dr);
    dr = ();
    dr["ID"] = 3;
    dr["Name"] = "Wang Wu";
    dr["CreateTime"] = ;
    (dr);
    return dt;
}

XML results:

&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;DataTable&gt;
  &lt;xs:schema  xmlns="" xmlns:xs="http:///2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"&gt;
    &lt;xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="NewDt" msdata:UseCurrentLocale="true"&gt;
      &lt;xs:complexType&gt;
        &lt;xs:choice minOccurs="0" maxOccurs="unbounded"&gt;
          &lt;xs:element name="NewDt"&gt;
            &lt;xs:complexType&gt;
              &lt;xs:sequence&gt;
                &lt;xs:element name="ID" type="xs:int" minOccurs="0" /&gt;
                &lt;xs:element name="Name" type="xs:string" minOccurs="0" /&gt;
                &lt;xs:element name="CreateTime" type="xs:dateTime" minOccurs="0" /&gt;
              &lt;/xs:sequence&gt;
            &lt;/xs:complexType&gt;
          &lt;/xs:element&gt;
        &lt;/xs:choice&gt;
      &lt;/xs:complexType&gt;
    &lt;/xs:element&gt;
  &lt;/xs:schema&gt;
  &lt;diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"&gt;
    &lt;DocumentElement&gt;
      &lt;NewDt diffgr: msdata:rowOrder="0" diffgr:hasChanges="inserted"&gt;
        &lt;ID&gt;1&lt;/ID&gt;
        &lt;Name&gt;Zhang San&lt;/Name&gt;
        &lt;CreateTime&gt;2018-10-04T16:06:10.8004082+08:00&lt;/CreateTime&gt;
      &lt;/NewDt&gt;
      &lt;NewDt diffgr: msdata:rowOrder="1" diffgr:hasChanges="inserted"&gt;
        &lt;ID&gt;2&lt;/ID&gt;
        &lt;Name&gt;Li Si&lt;/Name&gt;
        &lt;CreateTime&gt;2018-10-04T16:06:10.8004082+08:00&lt;/CreateTime&gt;
      &lt;/NewDt&gt;
      &lt;NewDt diffgr: msdata:rowOrder="2" diffgr:hasChanges="inserted"&gt;
        &lt;ID&gt;3&lt;/ID&gt;
        &lt;Name&gt;Wang Wu&lt;/Name&gt;
        &lt;CreateTime&gt;2018-10-04T16:06:10.8004082+08:00&lt;/CreateTime&gt;
      &lt;/NewDt&gt;
    &lt;/DocumentElement&gt;
  &lt;/diffgr:diffgram&gt;
&lt;/DataTable&gt;

2. Explanation and explanation of commonly used Attributes in 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。

By using these properties with the relevant properties of the model class, you can freely set the specific format of the relevant XML.

Comprehensive example: Serialize class information into XML

Example requirements:

(1) Each XML node starts with "My".

(2) Class ID and student ID fields are expressed in XML node attributes, and other fields are expressed in the form of XML nodes.

(3) Since the student's email address involves sensitive information, it does not participate in serialization.

2.1 Create a class information class ()

using ;
using ;
/// &lt;summary&gt;
/// Class information category/// &lt;/summary&gt;
[XmlRootAttribute("MyClassInfo", Namespace = "ABC_123", IsNullable = false)] 
public class ClassInfo
{
    /// &lt;summary&gt;
    /// Class ID    /// &lt;/summary&gt;
    [XmlAttribute("MyClassID")]
    public int ClassID { get; set; }
    /// &lt;summary&gt;
    /// Class name    /// &lt;/summary&gt;
    [XmlElementAttribute("MyClassName", IsNullable = false)] 
    public string ClassName { get; set; }
    /// &lt;summary&gt;
    /// The squad leader    /// &lt;/summary&gt;
    [XmlElementAttribute("MyTeacher", IsNullable = false)] 
    public string Teacher { get; set; }
    /// &lt;summary&gt;
    /// Student List    /// &lt;/summary&gt;
    [XmlArrayAttribute("MyStudents")]  
    public List&lt;Student&gt; StudentList { get; set; }
}

2.2 Create student information class ()

using ;
/// &lt;summary&gt;
/// Student Information/// &lt;/summary&gt;
[XmlRootAttribute("MyStudent", IsNullable = false)] 
public class Student
{
    /// &lt;summary&gt;
    /// Student ID    /// &lt;/summary&gt;
    [XmlAttribute("MyStuID")]
    public int StuID { get; set; }
    /// &lt;summary&gt;
    /// Student name    /// &lt;/summary&gt;
    [XmlElementAttribute("MyStuName", IsNullable = false)] 
    public string StuName { get; set; }
    /// &lt;summary&gt;
    /// gender    /// &lt;/summary&gt;
    [XmlElementAttribute("MySex", IsNullable = false)] 
    public string Sex { get; set; }
    /// &lt;summary&gt;
    /// Mail    /// &lt;/summary&gt;
    [XmlIgnoreAttribute] 
    public string Email { get; set; }
}

2.3 Convert class information to XML

/// &lt;summary&gt;
/// Convert class information to XML/// &lt;/summary&gt;
public static void ClassInfoToXml()
{
    //Get class information    ClassInfo classInfo = GetClassInfo();
    //Convert class information to XML    string classXml = (classInfo);
}
/// &lt;summary&gt;
/// Get class information/// &lt;/summary&gt;
public static ClassInfo GetClassInfo()
{
    //Create class information    ClassInfo classInfo = new ClassInfo();
     = 1;
     = "Class 1st Grade (5)";
     = "Teacher Li";
    //Create a student list    List&lt;Student&gt; studentList = new List&lt;Student&gt;();
    (new Student() { StuID = 1, StuName = "Zhang San", Sex = "male", Email = "zhangsan@" });
    (new Student() { StuID = 2, StuName = "Li Si", Sex = "female", Email = "lisi@" });
    (new Student() { StuID = 3, StuName = "Wang Wu", Sex = "male", Email = "wangwu@" });
     = studentList;
    return classInfo;
}

XML results:

&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;MyClassInfo xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:xsd="http:///2001/XMLSchema" MyClassID="1" xmlns="ABC_123"&gt;
  &lt;MyClassName&gt;First year of high school(5)class&lt;/MyClassName&gt;
  &lt;MyTeacher&gt;Teacher Li&lt;/MyTeacher&gt;
  &lt;MyStudents&gt;
    &lt;Student MyStuID="1"&gt;
      &lt;MyStuName&gt;Zhang San&lt;/MyStuName&gt;
      &lt;MySex&gt;male&lt;/MySex&gt;
    &lt;/Student&gt;
    &lt;Student MyStuID="2"&gt;
      &lt;MyStuName&gt;Li Si&lt;/MyStuName&gt;
      &lt;MySex&gt;female&lt;/MySex&gt;
    &lt;/Student&gt;
    &lt;Student MyStuID="3"&gt;
      &lt;MyStuName&gt;Wang Wu&lt;/MyStuName&gt;
      &lt;MySex&gt;male&lt;/MySex&gt;
    &lt;/Student&gt;
  &lt;/MyStudents&gt;
&lt;/MyClassInfo&gt;

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.