將XML轉換為實體


需求

將XML文件中的數據經過轉換后插入到數據庫中。

參考

C#實體類和XML的相互轉換

https://blog.csdn.net/pan_junbiao/article/details/82938027

遇到的問題

錯誤描述

XML反序列化出錯,XML 文檔(2, 2)中有錯誤

解決方案

在實體類的字段要加上XmlElement屬性

https://www.cnblogs.com/wuyunblog/p/6625747.html

具體實例

實體類和XML轉換的幫助類

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using System.Xml.Serialization;
 8 
 9 namespace conDealXML
10 {
11     public static class XmlSerializeHelper
12     {
13 
14         /// <summary>
15         /// 將實體對象轉換成XML
16         /// </summary>
17         /// <typeparam name="T">實體類型</typeparam>
18         /// <param name="obj">實體對象</param>
19         public static string XmlSerialize<T>(T obj)
20         {
21             try
22             {
23                 using (StringWriter sw = new StringWriter())
24                 {
25                     Type t = obj.GetType();
26                     XmlSerializer serializer = new XmlSerializer(obj.GetType());
27                     serializer.Serialize(sw, obj);
28                     sw.Close();
29                     return sw.ToString();
30                 }
31             }
32             catch (Exception ex)
33             {
34                 throw new Exception("將實體對象轉換成XML異常", ex);
35             }
36         }
37 
38         /// <summary>
39         /// 將XML轉換成實體對象
40         /// </summary>
41         /// <typeparam name="T">實體類型</typeparam>
42         /// <param name="strXML">XML</param>
43         public static T DESerializer<T>(string strXML) where T : class
44         {
45             try
46             {
47                 using (StringReader sr = new StringReader(strXML))
48                 {
49                     XmlSerializer serializer = new XmlSerializer(typeof(T));
50                     return serializer.Deserialize(sr) as T;
51                 }
52             }
53             catch (Exception ex)
54             {
55                 throw new Exception("將XML轉換成實體對象異常", ex);
56             }
57 
58         }
59     }
60 }
View Code

實體類

 1 using System;
 2 using System.Xml.Serialization;
 3 namespace Model
 4 {
 5     /// <summary>
 6     /// 功能: 實體類 (權限)
 7     /// 創建人:CodeSmith     
 8     /// 創建日期:2019/12/25    
 9     /// </summary>
10     [Serializable]
11     [XmlRoot(ElementName = "Action")]
12     public partial class Action
13     {
14        public Action() 
15        {    }       
16         #region Model
17         /// <summary>
18         /// 權限ID
19         /// </summary>
20         public short? ActionID {get; set;}
21         /// <summary>
22         /// 權限名字
23         /// </summary>
24         public string Name {get; set;}
25         /// <summary>
26         /// 權限標志代碼(用於功能的判定)
27         /// </summary>
28         public string Code {get; set;}
29         /// <summary>
30         /// 權限的路徑
31         /// </summary>
32         public string Url {get; set;}
33         /// <summary>
34         /// 排序
35         /// </summary>
36         public short? Sort {get; set;}
37         /// <summary>
38         /// 權限類型
39         /// </summary>
40         public int? ActionType {get; set;}
41         /// <summary>
42         /// 備注
43         /// </summary>
44         public string Memo {get; set;}
45         /// <summary>
46         /// 審核狀態
47         /// </summary>
48         public short? Check {get; set;}
49         /// <summary>
50         /// 添加時間
51         /// </summary>
52         public DateTime? InsertTime {get; set;}
53         /// <summary>
54         /// 修改時間
55         /// </summary>
56         public DateTime? ModifyTime {get; set;}
57         #endregion
58     }
59 }
View Code

XML文件

 1 <?xml version="1.0" encoding="gb2312"?>
 2 <MyConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 3     <Roles>
 4         <Role>
 5             <Actions>
 6                 <Action>
 7                     <ActionID>133</ActionID>
 8                     <Name>用戶查詢</Name>
 9                     <Code>041303</Code>
10                     <Url>/AddValue/addvalue_list</Url>
11                     <Sort>4</Sort>
12                     <ActionType>0</ActionType>
13                     <Check>1</Check>
14                     <InsertTime>2019-12-24T11:18:00</InsertTime>
15                     <ModifyTime xsi:nil="true" />
16                 </Action>
17             </Actions>
18             <Menus>
19                 <Menu>
20                     <MenuID>165</MenuID>
21                     <Title>用戶管理</Title>
22                     <ParentID>160</ParentID>
23                     <Layer>4</Layer>
24                     <Path>0/1/3/160</Path>
25                     <Sort>12</Sort>
26                     <Url>http://</Url>
27                     <Image>http://</Image>
28                     <IsVip>false</IsVip>
29                     <MenuType>0</MenuType>
30                     <Level>0</Level>
31                     <Check>1</Check>
32                     <InsertTime>2019-12-21T09:21:00</InsertTime>
33                     <ModifyTime>2019-12-21T09:23:00</ModifyTime>
34                 </Menu>
35             </Menus>
36             <RoleID></RoleID>
37             <Name>超級管理員</Name>
38         </Role>
39         <Role>
40         </Role>
41     </Roles>
42 </MyConfig>
View Code

控制台程序,執行轉換的過程

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Xml;
 7 
 8 namespace conDealXML
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             XmlDocument doc = new XmlDocument();
15             doc.Load("Roles.Config");
16 
17             XmlNode xn_MyConfig = doc.SelectSingleNode("MyConfig");
18             XmlNodeList xnl_Roles = xn_MyConfig.ChildNodes;
19             XmlNode xn_Roles_Roles = xnl_Roles[0];
20             XmlNodeList xnl_Roles_Role = xn_Roles_Roles.ChildNodes;
21             XmlNode xn_Role_Admin = xnl_Roles_Role[0];//第一個Role,為超級管理員
22             XmlNodeList xnl_Role_Admin = xn_Role_Admin.ChildNodes;
23             foreach (XmlNode item in xnl_Role_Admin)
24             {
25                 if (item.Name == "Actions")
26                 {
27                     XmlNodeList xnl_Actions = item.ChildNodes;//獲取到所有的Action
28                     foreach (XmlNode xn in xnl_Actions)
29                     {
30                         Model.Action model = XmlSerializeHelper.DESerializer<Model.Action>(xn.OuterXml);
31                         new DAL.Action().Add(model);
32                     }
33                 }
34                 if (item.Name == "Menus")
35                 {
36                     XmlNodeList xnl_Menus = item.ChildNodes;//獲取到所有的Action
37                     foreach (XmlNode xn in xnl_Menus)
38                     {
39                         Model.Menu model = XmlSerializeHelper.DESerializer<Model.Menu>(xn.OuterXml);
40                         new DAL.Menu().Add(model);
41                     }
42                 }
43             }
44 
45             Console.ReadKey();
46         }
47     }
48 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM