原帖地址:https://www.cnblogs.com/wuxdcsharp/p/9797446.html
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml; namespace CommonLib { public class XMLHelper { public XMLHelper() { } public void Create<T>(string xmlPath, List<T> updateXMLs) { XmlDocument document = new XmlDocument(); Type type = typeof(T); document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-8", null)); XmlElement root = document.CreateElement(type.Name + "Collection"); PropertyInfo[] properties = type.GetProperties(); foreach (var updateXml in updateXMLs) { XmlElement parentElememt = document.CreateElement(type.Name); foreach (PropertyInfo property in properties) { XmlElement element = document.CreateElement(property.Name); element.InnerText = updateXml.GetPropertyValue(property).ToString(); parentElememt.AppendChild(element); } root.AppendChild(parentElememt); } document.AppendChild(root); document.Save(xmlPath); } public List<T> Read<T>(string updatexml) where T : new() { XmlDocument document = new XmlDocument(); document.Load(updatexml); List<T> tList = new List<T>(); foreach (XmlNode node in document.ChildNodes[1].ChildNodes) { T t = new T(); foreach (XmlNode childNode in node.ChildNodes) { t.SetPropertyValue(childNode.Name, childNode.InnerText); } tList.Add(t); } return tList; } public List<T> ReadContext<T>(string context) where T : new() { XmlDocument document = new XmlDocument(); byte[] bytes = Encoding.UTF8.GetBytes(context); MemoryStream ms = new MemoryStream(bytes); ms.Seek(0, SeekOrigin.Begin); document.Load(ms); List<T> tList = new List<T>(); foreach (XmlNode node in document.ChildNodes[1].ChildNodes) { T t = new T(); foreach (XmlNode childNode in node.ChildNodes) { t.SetPropertyValue(childNode.Name, childNode.InnerText); } tList.Add(t); } return tList; } } }