using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Reflection; using System.Collections.Specialized; using System.Xml.Serialization; using System.IO; namespace Ant.Frame { //XML操作工具类代码 /// /// xml操作工具类 /// public class XmlUtils { #region Fields /// /// xml文件物理地址 /// private string xmlFilePath = String.Empty; #endregion #region Constructor /// /// 构造 /// public XmlUtils() { } /// /// 构造 /// /// xml文件物理地址 public XmlUtils(string path) { xmlFilePath = path; } #endregion #region Methods /// /// 读取xml数据,并转换成对象 /// /// 对象类名 /// 类实例对象 /// 节点名称 public void LoadXml(ref T obj, string nodeName) { Type oType = obj.GetType(); XmlDocument oXmlDocument = new XmlDocument(); oXmlDocument.Load(xmlFilePath); foreach (XmlNode oXmlNode in oXmlDocument.SelectSingleNode(nodeName).ChildNodes) { string name = oXmlNode.Name; string value = oXmlNode.InnerText; foreach (PropertyInfo oPropertyInfo in oType.GetProperties()) { if (oPropertyInfo.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) { try { oPropertyInfo.SetValue(obj, Convert.ChangeType(value, oPropertyInfo.PropertyType), null); } catch { } break; } } } } /// /// 将对象以xml文件存储 /// /// 对象类名 /// 类实例 /// 生成的xml的根节点名称 /// xml的文本编码 public void SaveXml(T obj, string nodeName, string encoding) { StringDictionary dic = new StringDictionary(); Type oType = obj.GetType(); foreach (PropertyInfo oPropertyInfo in oType.GetProperties()) { try { object propertyValue = oPropertyInfo.GetValue(obj, null); string valueAsString = propertyValue.ToString(); if (propertyValue.Equals(null)) { valueAsString = String.Empty; } if (propertyValue.Equals(Int32.MinValue)) { valueAsString = String.Empty; } if (propertyValue.Equals(Decimal.MinValue)) { valueAsString = String.Empty; } dic.Add(oPropertyInfo.Name, valueAsString); } catch { } } SaveXml(dic, nodeName, encoding); } /// /// 将对象以xml文件存储 /// /// 键值对象 /// 生成的xml的根节点名称 /// xml的文本编码 public void SaveXml(StringDictionary dic, string nodeName, string encoding) { XmlWriterSettings oXmlWriterSettings = new XmlWriterSettings(); oXmlWriterSettings.Encoding = Encoding.GetEncoding(encoding); oXmlWriterSettings.Indent = true; using (XmlWriter oXmlWriter = XmlWriter.Create(xmlFilePath, oXmlWriterSettings)) { oXmlWriter.WriteStartElement(nodeName); foreach (string key in dic.Keys) { oXmlWriter.WriteElementString(key, dic[key]); } oXmlWriter.WriteEndElement(); } } /// /// 将对象串行化到XML /// /// /// public void Serialize(T obj) { XmlSerializer oXmlSerializer = new XmlSerializer(obj.GetType()); using (Stream oStream = new FileStream(xmlFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)) { oXmlSerializer.Serialize(oStream, obj); } } /// /// 将XML反串行到对象 /// /// /// public void Deserialize(ref T obj) { XmlSerializer oXmlSerializer = new XmlSerializer(typeof(T)); using (Stream oStream = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { obj = (T)oXmlSerializer.Deserialize(oStream); } } #endregion } }