VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • C#教程之XML操作类

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Reflection;
 5 using System.Text;
 6 using System.Xml;
 7 
 8 namespace CommonLib
 9 {
10     public class XMLHelper
11     {
12         public XMLHelper()
13         {
14 
15         }
16 
17         public void Create<T>(string xmlPath, List<T> updateXMLs)
18         {
19             XmlDocument document = new XmlDocument();
20             Type type = typeof(T);
21             document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-8", null));
22             XmlElement root = document.CreateElement(type.Name + "Collection");
23             PropertyInfo[] properties = type.GetProperties();
24             foreach (var updateXml in updateXMLs)
25             {
26                 XmlElement parentElememt = document.CreateElement(type.Name);
27                 foreach (PropertyInfo property in properties)
28                 {
29                     XmlElement element = document.CreateElement(property.Name);
30                     element.InnerText = updateXml.GetPropertyValue(property).ToString();
31                     parentElememt.AppendChild(element);
32                 }
33                 root.AppendChild(parentElememt);
34             }
35             document.AppendChild(root);
36             document.Save(xmlPath);
37         }
38 
39         public List<T> Read<T>(string updatexml) where T : new()
40         {
41             XmlDocument document = new XmlDocument();
42             document.Load(updatexml);
43             List<T> tList = new List<T>();
44             foreach (XmlNode node in document.ChildNodes[1].ChildNodes)
45             {
46                 T t = new T();
47                 foreach (XmlNode childNode in node.ChildNodes)
48                 {
49                     t.SetPropertyValue(childNode.Name, childNode.InnerText);
50                 }
51                 tList.Add(t);
52             }
53             return tList;
54         }
55 
56 
57         public List<T> ReadContext<T>(string context) where T : new()
58         {
59             XmlDocument document = new XmlDocument();
60             byte[] bytes = Encoding.UTF8.GetBytes(context);
61             MemoryStream ms = new MemoryStream(bytes);
62             ms.Seek(0, SeekOrigin.Begin);
63             document.Load(ms);
64             List<T> tList = new List<T>();
65             foreach (XmlNode node in document.ChildNodes[1].ChildNodes)
66             {
67                 T t = new T();
68                 foreach (XmlNode childNode in node.ChildNodes)
69                 {
70                     t.SetPropertyValue(childNode.Name, childNode.InnerText);
71                 }
72                 tList.Add(t);
73             }
74             return tList;
75         }
76     }
77 }
复制代码

相关教程