using System; using System.Data; using System.Configuration; using System.Web; using System.Xml; using System.Xml.Serialization; using System.IO; using System.Collections.Generic; using System.Text; namespace GTA.DC.MTAC.Client.BLL { /// <summary> /// 描述:XML操作类 /// 作者: /// 时间:2011-5-18 /// </summary> public class XmlHelper { /// <summary> /// 读取数据 /// </summary> /// <param name="path">路径</param> /// <param name="node">节点</param> /// <param name="attribute">属性名,非空时返回该属性值,否则返回串联值</param> /// <returns>string</returns> /************************************************** * 使用示列: * XmlHelper.Read(path, "/Node", "") * XmlHelper.Read(path, "/Node/Element[@Attribute='Name']", "Attribute") ************************************************/ public string Read(string path, string node, string attribute) { string value = ""; try { XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNode xn = doc.SelectSingleNode(node); value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value); } catch { } return value; } /// <summary> /// 插入数据 /// </summary> /// <param name="path">路径</param> /// <param name="node">节点</param> /// <param name="element">元素名,非空时插入新元素,否则在该元素中插入属性</param> /// <param name="attribute">属性名,非空时插入该元素属性值,否则插入元素值</param> /// <param name="value">值</param> /// <returns></returns> /************************************************** * 使用示列: * XmlHelper.Insert(path, "/Node", "Element", "", "Value") * XmlHelper.Insert(path, "/Node", "Element", "Attribute", "Value") * XmlHelper.Insert(path, "/Node", "", "Attribute", "Value") ************************************************/ public void Insert(string path, string node, string element, string attribute, string value) { try { XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNode xn = doc.SelectSingleNode(node); if (element.Equals("")) { if (!attribute.Equals("")) { XmlElement xe = (XmlElement)xn; xe.SetAttribute(attribute, value); } } else { XmlElement xe = doc.CreateElement(element); if (attribute.Equals("")) xe.InnerText = value; else xe.SetAttribute(attribute, value); xn.AppendChild(xe); } doc.Save(path); } catch { } } /// <summary> /// 修改数据 /// </summary> /// <param name="path">路径</param> /// <param name="node">节点</param> /// <param name="attribute">属性名,非空时修改该节点属性值,否则修改节点值</param> /// <param name="value">值</param> /// <returns></returns> /************************************************** * 使用示列: * XmlHelper.Insert(path, "/Node", "", "Value") * XmlHelper.Insert(path, "/Node", "Attribute", "Value") ************************************************/ public void Update(string path, string node, string attribute, string value) { try { XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNode xn = doc.SelectSingleNode(node); XmlElement xe = (XmlElement)xn; if (attribute.Equals("")) xe.InnerText = value; else xe.SetAttribute(attribute, value); doc.Save(path); } catch { } } /// <summary> /// 删除数据 /// </summary> /// <param name="path">路径</param> /// <param name="node">节点</param> /// <param name="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param> /// <param name="value">值</param> /// <returns></returns> /************************************************** * 使用示列: * XmlHelper.Delete(path, "/Node", "") * XmlHelper.Delete(path, "/Node", "Attribute") ************************************************/ public void Delete(string path, string node, string attribute) { try { XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNode xn = doc.SelectSingleNode(node); XmlElement xe = (XmlElement)xn; if (attribute.Equals("")) xn.ParentNode.RemoveChild(xn); else xe.RemoveAttribute(attribute); doc.Save(path); } catch { } } private XmlDocument xmlDoc; /// <summary> /// 加载xml文件 /// </summary> /// <param name="path">xml文件的物理路径</param> private void LoadXml(string path, string node_root) { xmlDoc = new XmlDocument(); //判断xml文件是否存在 if (!System.IO.File.Exists(path)) { //创建xml 声明节点 XmlNode xmlnode = xmlDoc.CreateNode(System.Xml.XmlNodeType.XmlDeclaration, "", ""); //添加上述创建和 xml声明节点 xmlDoc.AppendChild(xmlnode); //创建xml dbGuest 元素(根节点) XmlElement xmlelem = xmlDoc.CreateElement("", node_root, ""); xmlDoc.AppendChild(xmlelem); try { xmlDoc.Save(path); } catch (Exception ex) { throw ex; } xmlDoc.Load(path); } else { //加载xml文件 xmlDoc.Load(path); } GC.Collect(); } /// <summary> /// 添加xml子节点 /// </summary> /// <param name="path">xml文件的物理路径</param> /// <param name="node_root">根节点名称</param> /// <param name="node_name">添加的子节点名称</param> /// <param name="node_text">子节点文本</param> public void addElement(string path, string node_root, string node_name, string node_text, string att_name, string att_value) { LoadXml(path, node_root); XmlNodeList nodeList = xmlDoc.SelectSingleNode(node_root).ChildNodes;//获取bookstore节点的所有子节点 //判断是否有节点,有节点就遍历所有子节点,看看有没有重复节点,没节点就添加一个新节点 if (nodeList.Count > 0) { foreach (XmlNode xn in nodeList)//遍历所有子节点 { XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型 if (xe.GetAttribute(att_name) != att_value) { XmlNode xmldocSelect = xmlDoc.SelectSingleNode(node_root); //选中根节点 XmlElement son_node = xmlDoc.CreateElement(node_name); //添加子节点 son_node.SetAttribute(att_name, att_value); //设置属性 son_node.InnerText = node_text; //添加节点文本 xmldocSelect.AppendChild(son_node); //添加子节点 xmlDoc.Save(path); //保存xml文件 break; } } } else { XmlNode xmldocSelect = xmlDoc.SelectSingleNode(node_root); //选中根节点 XmlElement son_node = xmlDoc.CreateElement(node_name); //添加子节点 son_node.SetAttribute(att_name, att_value); //设置属性 son_node.InnerText = node_text; //添加节点文本 xmldocSelect.AppendChild(son_node); //添加子节点 xmlDoc.Save(path); //保存xml文件 } } /// <summary> /// 修改节点的内容 /// </summary> /// <param name="path">xml文件的物理路径</param> /// <param name="node_root">根节点名称</param> /// <param name="new_text">节点的新内容</param> /// <param name="att_name">节点的属性名</param> /// <param name="att_value">节点的属性值</param> public void UpdateElement(string path, string node_root, string new_text, string att_name, string att_value) { LoadXml(path, node_root); XmlNodeList nodeList = xmlDoc.SelectSingleNode(node_root).ChildNodes;//获取bookstore节点的所有子节点 foreach (XmlNode xn in nodeList)//遍历所有子节点 { XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型 if (xe.GetAttribute(att_name) == att_value) { xe.InnerText = new_text; //内容赋值 xmlDoc.Save(path);//保存 break; } } } /// <summary> /// 删除节点 /// </summary> /// <param name="path">xml文件的物理路径</param> /// <param name="node_root">根节点名称</param> /// <param name="att_name">节点的属性名</param> /// <param name="att_value">节点的属性值</param> public void deleteNode(string path, string node_root, string att_name, string att_value) { LoadXml(path, node_root); XmlNodeList nodeList = xmlDoc.SelectSingleNode(node_root).ChildNodes; XmlNode root = xmlDoc.SelectSingleNode(node_root); foreach (XmlNode xn in nodeList) { XmlElement xe = (XmlElement)xn; if (xe.GetAttribute(att_name) == att_value) { //xe.RemoveAttribute("name");//删除name属性 xe.RemoveAll();//删除该节点的全部内容 root.RemoveChild(xe); xmlDoc.Save(path);//保存 break; } } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filePath"></param> /// <param name="obj"></param> public static void Serialize<T>(string filePath, T[] array) where T : new() { if (string.IsNullOrEmpty(filePath) || array == null || array.Length == 0) { return; } try { XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory(); XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(array.GetType(), typeof(T).Name); Stream stream = new FileStream(filePath, FileMode.Create); xmlSerializer.Serialize(stream, array); stream.Close(); } catch { } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filePath"></param> /// <param name="obj"></param> public static void Serialize<T>(string filePath, List<T> array) where T : new() { if (string.IsNullOrEmpty(filePath) || array == null || array.Count == 0) { return; } try { XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory(); XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(array.GetType(), typeof(T).Name); Stream stream = new FileStream(filePath, FileMode.Create); xmlSerializer.Serialize(stream, array); stream.Close(); } catch { } } /// <summary> /// /// </summary> /// <param name="filePath"></param> /// <param name="obj"></param> public static void Serialize(string filePath, object obj) { if (string.IsNullOrEmpty(filePath) || obj == null) { return; } try { XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory(); XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(obj.GetType(), obj.GetType().Name); Stream stream = new FileStream(filePath, FileMode.Create); xmlSerializer.Serialize(stream, obj); stream.Close(); } catch { } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filePath"></param> /// <returns></returns> public static List<T> Deserialize<T>(string filePath) where T : new() { List<T> results = new List<T>(); if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) { return results; } object obj = null; try { XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory(); XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(typeof(T[]), typeof(T).Name); Stream stream = new FileStream(filePath, System.IO.FileMode.Open); obj = xmlSerializer.Deserialize(stream); stream.Close(); results.AddRange(obj as T[]); } catch { } return results; } /// <summary> /// /// </summary> /// <param name="filePath"></param> /// <param name="targetType"></param> /// <returns></returns> public static object Deserialize(string filePath, Type targetType) { if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath) || targetType == null) { return null; } object obj = null; try { XmlSerializerFactory xmlSerializerFactory = new XmlSerializerFactory(); XmlSerializer xmlSerializer = xmlSerializerFactory.CreateSerializer(targetType, targetType.Name); Stream stream = new FileStream(filePath, FileMode.Open); obj = xmlSerializer.Deserialize(stream); stream.Close(); } catch { } return obj; } /**/ /// <summary> /// 将DataTable对象转换成XML字符串 /// </summary> /// <param name="dt">DataTable对象</param> /// <returns>XML字符串</returns> public static string CDataToXml(DataTable dt) { if (dt != null) { MemoryStream ms = null; XmlTextWriter XmlWt = null; try { ms = new MemoryStream(); //根据ms实例化XmlWt XmlWt = new XmlTextWriter(ms, Encoding.Unicode); //获取ds中的数据 dt.WriteXml(XmlWt); int count = (int)ms.Length; byte[] temp = new byte[count]; ms.Seek(0, SeekOrigin.Begin); ms.Read(temp, 0, count); //返回Unicode编码的文本 UnicodeEncoding ucode = new UnicodeEncoding(); string returnValue = ucode.GetString(temp).Trim(); return returnValue; } catch (System.Exception ex) { throw ex; } finally { //释放资源 if (XmlWt != null) { XmlWt.Close(); ms.Close(); ms.Dispose(); } } } else { return ""; } } /// <summary> /// 把XML字符串转成DataTable /// </summary> /// <param name="xmlData"></param> /// <returns></returns> public static DataTable ConvertXMLToDataSet(string xmlData) { StringReader stream = null; XmlTextReader reader = null; try { DataSet xmlDS = new DataSet(); stream = new StringReader(xmlData); reader = new XmlTextReader(stream); xmlDS.ReadXml(reader); return xmlDS.Tables[0]; } catch (Exception ex) { string strTest = ex.Message; return null; } finally { if (reader != null) reader.Close(); } } } }