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<T>(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); } } /// <summary> /// Convert XML to entity object /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <param name="strXML">XML</param> public static T DESerializer<T>(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.
/// <summary> /// User information category/// </summary> public class UserInfo { /// <summary> /// serial number /// </summary> public int ID { get; set; } /// <summary> /// Name /// </summary> public string Name { get; set; } /// <summary> /// Creation time /// </summary> public DateTime? CreateTime { get; set; } }
1.1 Example 1: Convert List and XML to each other
/// <summary> /// Convert List and XML to each other/// </summary> public static void ListToXmlTest() { //Get user list List<UserInfo> userList = GetUserList(); //Convert entity objects to XML string xmlResult = (userList); //Convert XML to entity object List<UserInfo> deResult = <List<UserInfo>>(xmlResult); } /// <summary> /// Get a list of user information/// </summary> public static List<UserInfo> GetUserList() { List<UserInfo> userList = new List<UserInfo>(); (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:
<?xml version="1.0" encoding="utf-16"?> <ArrayOfUserInfo xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:xsd="http:///2001/XMLSchema"> <UserInfo> <ID>1</ID> <Name>Zhang San</Name> <CreateTime>2018-10-04T15:59:53.7761027+08:00</CreateTime> </UserInfo> <UserInfo> <ID>2</ID> <Name>Li Si</Name> <CreateTime>2018-10-04T15:59:54.9571044+08:00</CreateTime> </UserInfo> <UserInfo> <ID>2</ID> <Name>Wang Wu</Name> <CreateTime xsi:nil="true" /> </UserInfo> </ArrayOfUserInfo>
1.2 Example 2: Convert DataTable and XML to each other
/// <summary> /// Convert DataTable and XML to each other/// </summary> public static void DataTableToXmlTest() { //Create DataTable object DataTable dt = CreateDataTable(); //Convert DataTable to XML string xmlResult = (dt); //Convert XML to DataTable DataTable deResult = <DataTable>(xmlResult); } /// <summary> /// Create DataTable object/// </summary> 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:
<?xml version="1.0" encoding="utf-16"?> <DataTable> <xs:schema xmlns="" xmlns:xs="http:///2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="NewDt" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="NewDt"> <xs:complexType> <xs:sequence> <xs:element name="ID" type="xs:int" minOccurs="0" /> <xs:element name="Name" type="xs:string" minOccurs="0" /> <xs:element name="CreateTime" type="xs:dateTime" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <DocumentElement> <NewDt diffgr: msdata:rowOrder="0" diffgr:hasChanges="inserted"> <ID>1</ID> <Name>Zhang San</Name> <CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime> </NewDt> <NewDt diffgr: msdata:rowOrder="1" diffgr:hasChanges="inserted"> <ID>2</ID> <Name>Li Si</Name> <CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime> </NewDt> <NewDt diffgr: msdata:rowOrder="2" diffgr:hasChanges="inserted"> <ID>3</ID> <Name>Wang Wu</Name> <CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime> </NewDt> </DocumentElement> </diffgr:diffgram> </DataTable>
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 ; /// <summary> /// Class information category/// </summary> [XmlRootAttribute("MyClassInfo", Namespace = "ABC_123", IsNullable = false)] public class ClassInfo { /// <summary> /// Class ID /// </summary> [XmlAttribute("MyClassID")] public int ClassID { get; set; } /// <summary> /// Class name /// </summary> [XmlElementAttribute("MyClassName", IsNullable = false)] public string ClassName { get; set; } /// <summary> /// The squad leader /// </summary> [XmlElementAttribute("MyTeacher", IsNullable = false)] public string Teacher { get; set; } /// <summary> /// Student List /// </summary> [XmlArrayAttribute("MyStudents")] public List<Student> StudentList { get; set; } }
2.2 Create student information class ()
using ; /// <summary> /// Student Information/// </summary> [XmlRootAttribute("MyStudent", IsNullable = false)] public class Student { /// <summary> /// Student ID /// </summary> [XmlAttribute("MyStuID")] public int StuID { get; set; } /// <summary> /// Student name /// </summary> [XmlElementAttribute("MyStuName", IsNullable = false)] public string StuName { get; set; } /// <summary> /// gender /// </summary> [XmlElementAttribute("MySex", IsNullable = false)] public string Sex { get; set; } /// <summary> /// Mail /// </summary> [XmlIgnoreAttribute] public string Email { get; set; } }
2.3 Convert class information to XML
/// <summary> /// Convert class information to XML/// </summary> public static void ClassInfoToXml() { //Get class information ClassInfo classInfo = GetClassInfo(); //Convert class information to XML string classXml = (classInfo); } /// <summary> /// Get class information/// </summary> public static ClassInfo GetClassInfo() { //Create class information ClassInfo classInfo = new ClassInfo(); = 1; = "Class 1st Grade (5)"; = "Teacher Li"; //Create a student list List<Student> studentList = new List<Student>(); (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:
<?xml version="1.0" encoding="utf-16"?> <MyClassInfo xmlns:xsi="http:///2001/XMLSchema-instance" xmlns:xsd="http:///2001/XMLSchema" MyClassID="1" xmlns="ABC_123"> <MyClassName>First year of high school(5)class</MyClassName> <MyTeacher>Teacher Li</MyTeacher> <MyStudents> <Student MyStuID="1"> <MyStuName>Zhang San</MyStuName> <MySex>male</MySex> </Student> <Student MyStuID="2"> <MyStuName>Li Si</MyStuName> <MySex>female</MySex> </Student> <Student MyStuID="3"> <MyStuName>Wang Wu</MyStuName> <MySex>male</MySex> </Student> </MyStudents> </MyClassInfo>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.