using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.IO; using System.Xml; using System.Reflection; using System.Data; namespace XMLommon { public class XmlOperate { /// <summary> /// 泛型集合序列化到XML /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="filePath">XML文件路径</param> /// <param name="list">泛型集合</param> public void SerializerData<T>(string filePath,List<T> list) where T:new() { XmlSerializer xs = new XmlSerializer(typeof(List<T>)); FileStream fs = new FileStream(filePath,FileMode.OpenOrCreate,FileAccess.Write); xs.Serialize(fs,list); } /// <summary> /// 对象序列化到XML /// </summary> /// <typeparam name="T">对象</typeparam> /// <param name="filePath">XML文件路径</param> /// <param name="t">对象</param> public void SerializerData<T>(string filePath, T t) where T : new() { XmlSerializer xs = new XmlSerializer(typeof(T)); FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write); xs.Serialize(fs, t); } /// <summary> /// XML反序列化到泛型集合 /// </summary> /// <typeparam name="T">对象</typeparam> /// <param name="filePath">XML文件路径</param> /// <returns>泛型集合</returns> public List<T> DeserializerDataToList<T>(string filePath) where T :new() { List<T> list = new List<T>(); XmlSerializer xs = new XmlSerializer(typeof(List<T>)); Stream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read); list = (List<T>)xs.Deserialize(fs); return list; } /// <summary> /// XML反序列化到对象 /// </summary> /// <typeparam name="T">对象</typeparam> /// <param name="filePath">XML文件路径</param> /// <returns>对象</returns> public T DeserializerDataToObject<T>(string filePath) where T : new() { T t = new T(); XmlSerializer xs = new XmlSerializer(typeof(T)); FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read); t = (T)xs.Deserialize(fs); return t; } /// <summary> /// 加载XML /// </summary> /// <param name="filePath">文件路径</param> /// <param name="root_node">根节点</param> /// <returns>XmlDoc对象</returns> public XmlDocument LoadXml(string filePath,string root_node) { XmlDocument xmlDoc = new XmlDocument(); if (!File.Exists(filePath)) { XmlProcessingInstruction xpi = xmlDoc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\" "); xmlDoc.AppendChild(xpi); XmlElement xmlEle = xmlDoc.CreateElement(root_node); xmlDoc.AppendChild(xmlEle); try { xmlDoc.Save(filePath); } catch (Exception ex) { throw ex; } } xmlDoc.Load(filePath); return xmlDoc; } /// <summary> /// 获取XML数据并填充到DataTable /// </summary> /// <param name="filePath">文件路径</param> /// <param name="root_node">根节点</param> /// <returns>数据表</returns> public DataTable XmlToTable(string filePath, string root_node) { //判断文件是否存在,不存在则创建,否则直接读取数据 if (!File.Exists(filePath)) { XmlDocument xmlDoc = new XmlDocument(); XmlProcessingInstruction xpi = xmlDoc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\" "); xmlDoc.AppendChild(xpi); XmlElement xmlEle = xmlDoc.CreateElement(root_node); xmlDoc.AppendChild(xmlEle); try { xmlDoc.Save(filePath); } catch (Exception ex) { throw ex; } } DataSet ds = new DataSet(); ds.ReadXml(filePath); if (ds.Tables.Count>0) { return ds.Tables[0]; } return null; } // Xml结构的文件读到DataTable中 static DataTable XmlToDataTableByFile() { string fileName = "E:\\xmlsample.xml"; XmlDocument doc = new XmlDocument(); doc.Load(fileName); DataTable dt = new DataTable("song"); //以第一个元素song的子元素建立表结构 XmlNode songNode = doc.SelectSingleNode("/music/song[1]"); string colName; if (songNode != null) { for (int i = 0; i < songNode.ChildNodes.Count; i++) { colName = songNode.ChildNodes.Item(i).Name; dt.Columns.Add(colName); } } DataSet ds = new DataSet("music"); ds.Tables.Add(dt); //Xml所有song元素的子元素读到表song中,当然用dt也可以读。 ds.ReadXml(fileName); return dt; } /// <summary> /// 根据属性/值获取XmlElement节点 /// </summary> /// <param name="xmlDoc">XML文档</param> /// <param name="root_node">根节点</param> /// <param name="propertyName">属性</param> /// <param name="propertyValue">值</param> /// <returns>XmlElement节点</returns> public XmlElement GetXmlElementByProperty(XmlDocument xmlDoc, string root_node, string propertyName, string propertyValue) { XmlElement xmlEle; XmlNode xmlDocSelect = xmlDoc.SelectSingleNode(root_node); foreach (XmlNode nodes in xmlDocSelect.ChildNodes) { xmlEle = (XmlElement)nodes; if (xmlEle.GetAttribute(propertyName) == propertyValue) { return xmlEle; } } return null; } /// <summary> /// 根据属性获取值 /// </summary> /// <param name="xmlDoc">XML文档</param> /// <param name="root_node">根节点</param> /// <param name="propertyName">属性</param> /// <returns>XmlElement节点</returns> public string GetValueByProperty(XmlDocument xmlDoc, string root_node, string propertyName) { string value=""; XmlElement xmlEle; XmlNode xmlDocSelect = xmlDoc.SelectSingleNode(root_node); //只获取第一个子节点的值 XmlNode xmlNode = xmlDocSelect.ChildNodes[0]; xmlEle=(XmlElement)xmlNode; value = xmlEle.GetAttribute(propertyName); return value; } /// <summary> /// 添加XML节点 /// </summary> /// <typeparam name="T">对象</typeparam> /// <param name="filePath">文件路径</param> /// <param name="xmlDoc">XmlDocument对象</param> /// <param name="root_node">根节点</param> /// <param name="t">对象</param> public void AddXmlElement<T>(string filePath,XmlDocument xmlDoc,string root_node,T t) where T : new() { XmlNode xmlDocSelect = xmlDoc.SelectSingleNode(root_node); XmlElement xmlEle = xmlDoc.CreateElement(t.GetType().Name); //获取对象属性 PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); //遍历对象的属性,并获取属性的值 foreach (PropertyInfo item in properties) { string attName = item.Name; object value = item.GetValue(t,null); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { XmlAttribute xmlattr = xmlDoc.CreateAttribute(attName); xmlattr.Value = value.ToString(); xmlEle.Attributes.Append(xmlattr); } } xmlDocSelect.AppendChild(xmlEle); xmlDoc.Save(filePath); } /// <summary> /// 修改XML节点 /// </summary> /// <typeparam name="T">对象</typeparam> /// <param name="filePath">XML文件路径</param> /// <param name="xmlDoc">XmlDocument对象</param> /// <param name="xmlEle">根节点</param> /// <param name="t">对象</param> /// <returns>true or false</returns> public bool UpdateXmlElement<T>(string filePath, XmlDocument xmlDoc,XmlElement xmlEle, T t) where T : new() { bool result = false; try { //获取对象属性 PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); //遍历对象的属性,并获取属性的值 foreach (PropertyInfo item in properties) { string attName = item.Name; object value = item.GetValue(t, null); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) { xmlEle.SetAttribute(attName, value.ToString()); } } xmlDoc.Save(filePath); result = true; } catch (Exception ex) { throw new ApplicationException(ex.Message); } return result; } /// <summary> /// 删除一个XML节点或者全部XML节点 /// </summary> /// <param name="filePath">XML文件路径</param> /// <param name="xmlDoc">Xmldocument对象</param> /// <param name="root_node">根节点名称</param> /// <param name="propertyName">属性名称</param> /// <param name="propertyValue">属性值</param> /// <param name="isDeleteAll">是否全部删除,false为删除一个,true为全部删除</param> /// <returns>true or false</returns> public bool DeleteXmlElement(string filePath, XmlDocument xmlDoc, string root_node, string propertyName, string propertyValue,bool isDeleteAll) { XmlNode xmlDocSelect = xmlDoc.SelectSingleNode(root_node); if (!isDeleteAll) { foreach (XmlNode nodes in xmlDocSelect.ChildNodes) { XmlElement xmlEle = (XmlElement)nodes; if (xmlEle.GetAttribute(propertyName) == propertyValue) { xmlDocSelect.RemoveChild(nodes); xmlDoc.Save(filePath); return true; } } } else { xmlDocSelect.RemoveAll(); xmlDoc.Save(filePath); return true; } return false; } //将datatable表内容和架构写入xml文件保存 public bool SaveDataTabletoXml(string filename,DataTable dt) { try { dt.WriteXml(filename, XmlWriteMode.WriteSchema); return true; } catch (Exception e) { return false; } } //将Xml数据读到datatable中,必须是通过XmlWriteMode.WriteSchema写入架构的Xml文件 public DataTable LoadDataTableFromXml(string filename) { DataTable dt = new DataTable(); dt.ReadXml(filename); return dt; } } }
浙公网安备 33010602011771号