using System.Xml; using System.Data; namespace DotNet.Utilities { /// <summary> /// Xml的操作公共類 /// </summary> public class XmlHelper { #region 欄位定義 /// ...
using System.Xml; using System.Data; namespace DotNet.Utilities { /// <summary> /// Xml的操作公共類 /// </summary> public class XmlHelper { #region 欄位定義 /// <summary> /// XML文件的物理路徑 /// </summary> private string _filePath = string.Empty; /// <summary> /// Xml文檔 /// </summary> private XmlDocument _xml; /// <summary> /// XML的根節點 /// </summary> private XmlElement _element; #endregion #region 構造方法 /// <summary> /// 實例化XmlHelper對象 /// </summary> /// <param name="xmlFilePath">Xml文件的相對路徑</param> public XmlHelper(string xmlFilePath) { //獲取XML文件的絕對路徑 _filePath = SysHelper.GetPath(xmlFilePath); } #endregion #region 創建XML的根節點 /// <summary> /// 創建XML的根節點 /// </summary> private void CreateXMLElement() { //創建一個XML對象 _xml = new XmlDocument(); if (DirFile.IsExistFile(_filePath)) { //載入XML文件 _xml.Load(this._filePath); } //為XML的根節點賦值 _element = _xml.DocumentElement; } #endregion #region 獲取指定XPath表達式的節點對象 /// <summary> /// 獲取指定XPath表達式的節點對象 /// </summary> /// <param name="xPath">XPath表達式, /// 範例1: @"Skill/First/SkillItem", 等效於 @"//Skill/First/SkillItem" /// 範例2: @"Table[USERNAME='a']" , []表示篩選,USERNAME是Table下的一個子節點. /// 範例3: @"ApplyPost/Item[@itemName='崗位編號']",@itemName是Item節點的屬性. /// </param> public XmlNode GetNode(string xPath) { //創建XML的根節點 CreateXMLElement(); //返回XPath節點 return _element.SelectSingleNode(xPath); } #endregion #region 獲取指定XPath表達式節點的值 /// <summary> /// 獲取指定XPath表達式節點的值 /// </summary> /// <param name="xPath">XPath表達式, /// 範例1: @"Skill/First/SkillItem", 等效於 @"//Skill/First/SkillItem" /// 範例2: @"Table[USERNAME='a']" , []表示篩選,USERNAME是Table下的一個子節點. /// 範例3: @"ApplyPost/Item[@itemName='崗位編號']",@itemName是Item節點的屬性. /// </param> public string GetValue(string xPath) { //創建XML的根節點 CreateXMLElement(); //返回XPath節點的值 return _element.SelectSingleNode(xPath).InnerText; } #endregion #region 獲取指定XPath表達式節點的屬性值 /// <summary> /// 獲取指定XPath表達式節點的屬性值 /// </summary> /// <param name="xPath">XPath表達式, /// 範例1: @"Skill/First/SkillItem", 等效於 @"//Skill/First/SkillItem" /// 範例2: @"Table[USERNAME='a']" , []表示篩選,USERNAME是Table下的一個子節點. /// 範例3: @"ApplyPost/Item[@itemName='崗位編號']",@itemName是Item節點的屬性. /// </param> /// <param name="attributeName">屬性名</param> public string GetAttributeValue(string xPath, string attributeName) { //創建XML的根節點 CreateXMLElement(); //返回XPath節點的屬性值 return _element.SelectSingleNode(xPath).Attributes[attributeName].Value; } #endregion #region 新增節點 /// <summary> /// 1. 功能:新增節點。 /// 2. 使用條件:將任意節點插入到當前Xml文件中。 /// </summary> /// <param name="xmlNode">要插入的Xml節點</param> public void AppendNode(XmlNode xmlNode) { //創建XML的根節點 CreateXMLElement(); //導入節點 XmlNode node = _xml.ImportNode(xmlNode, true); //將節點插入到根節點下 _element.AppendChild(node); } /// <summary> /// 1. 功能:新增節點。 /// 2. 使用條件:將DataSet中的第一條記錄插入Xml文件中。 /// </summary> /// <param name="ds">DataSet的實例,該DataSet中應該只有一條記錄</param> public void AppendNode(DataSet ds) { //創建XmlDataDocument對象 XmlDataDocument xmlDataDocument = new XmlDataDocument(ds); //導入節點 XmlNode node = xmlDataDocument.DocumentElement.FirstChild; //將節點插入到根節點下 AppendNode(node); } #endregion #region 刪除節點 /// <summary> /// 刪除指定XPath表達式的節點 /// </summary> /// <param name="xPath">XPath表達式, /// 範例1: @"Skill/First/SkillItem", 等效於 @"//Skill/First/SkillItem" /// 範例2: @"Table[USERNAME='a']" , []表示篩選,USERNAME是Table下的一個子節點. /// 範例3: @"ApplyPost/Item[@itemName='崗位編號']",@itemName是Item節點的屬性. /// </param> public void RemoveNode(string xPath) { //創建XML的根節點 CreateXMLElement(); //獲取要刪除的節點 XmlNode node = _xml.SelectSingleNode(xPath); //刪除節點 _element.RemoveChild(node); } #endregion //刪除節點 #region 保存XML文件 /// <summary> /// 保存XML文件 /// </summary> public void Save() { //創建XML的根節點 CreateXMLElement(); //保存XML文件 _xml.Save(this._filePath); } #endregion //保存XML文件 #region 靜態方法 #region 創建根節點對象 /// <summary> /// 創建根節點對象 /// </summary> /// <param name="xmlFilePath">Xml文件的相對路徑</param> private static XmlElement CreateRootElement(string xmlFilePath) { //定義變數,表示XML文件的絕對路徑 string filePath = ""; //獲取XML文件的絕對路徑 filePath = SysHelper.GetPath(xmlFilePath); //創建XmlDocument對象 XmlDocument xmlDocument = new XmlDocument(); //載入XML文件 xmlDocument.Load(filePath); //返回根節點 return xmlDocument.DocumentElement; } #endregion #region 獲取指定XPath表達式節點的值 /// <summary> /// 獲取指定XPath表達式節點的值 /// </summary> /// <param name="xmlFilePath">Xml文件的相對路徑</param> /// <param name="xPath">XPath表達式, /// 範例1: @"Skill/First/SkillItem", 等效於 @"//Skill/First/SkillItem" /// 範例2: @"Table[USERNAME='a']" , []表示篩選,USERNAME是Table下的一個子節點. /// 範例3: @"ApplyPost/Item[@itemName='崗位編號']",@itemName是Item節點的屬性. /// </param> public static string GetValue(string xmlFilePath, string xPath) { //創建根對象 XmlElement rootElement = CreateRootElement(xmlFilePath); //返回XPath節點的值 return rootElement.SelectSingleNode(xPath).InnerText; } #endregion #region 獲取指定XPath表達式節點的屬性值 /// <summary> /// 獲取指定XPath表達式節點的屬性值 /// </summary> /// <param name="xmlFilePath">Xml文件的相對路徑</param> /// <param name="xPath">XPath表達式, /// 範例1: @"Skill/First/SkillItem", 等效於 @"//Skill/First/SkillItem" /// 範例2: @"Table[USERNAME='a']" , []表示篩選,USERNAME是Table下的一個子節點. /// 範例3: @"ApplyPost/Item[@itemName='崗位編號']",@itemName是Item節點的屬性. /// </param> /// <param name="attributeName">屬性名</param> public static string GetAttributeValue(string xmlFilePath, string xPath, string attributeName) { //創建根對象 XmlElement rootElement = CreateRootElement(xmlFilePath); //返回XPath節點的屬性值 return rootElement.SelectSingleNode(xPath).Attributes[attributeName].Value; } #endregion #endregion public static void SetValue(string xmlFilePath, string xPath, string newtext) { //string path = SysHelper.GetPath(xmlFilePath); //var queryXML = from xmlLog in xelem.Descendants("msg_log") // //所有名字為Bin的記錄 // where xmlLog.Element("user").Value == "Bin" // select xmlLog; //foreach (XElement el in queryXML) //{ // el.Element("user").Value = "LiuBin";//開始修改 //} //xelem.Save(path); } } }XmlHelper
using System; using System.Data; using System.IO; using System.Xml; namespace DotNet.Utilities { public class XMLProcess { #region 構造函數 public XMLProcess() { } public XMLProcess(string strPath) { this._XMLPath = strPath; } #endregion #region 公有屬性 private string _XMLPath; public string XMLPath { get { return this._XMLPath; } } #endregion #region 私有方法 /// <summary> /// 導入XML文件 /// </summary> /// <param name="XMLPath">XML文件路徑</param> private XmlDocument XMLLoad() { string XMLFile = XMLPath; XmlDocument xmldoc = new XmlDocument(); try { string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + XMLFile; if (File.Exists(filename)) xmldoc.Load(filename); } catch (Exception e) { } return xmldoc; } /// <summary> /// 導入XML文件 /// </summary> /// <param name="XMLPath">XML文件路徑</param> private static XmlDocument XMLLoad(string strPath) { XmlDocument xmldoc = new XmlDocument(); try { string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + strPath; if (File.Exists(filename)) xmldoc.Load(filename); } catch (Exception e) { } return xmldoc; } /// <summary> /// 返回完整路徑 /// </summary> /// <param name="strPath">Xml的路徑</param> private static string GetXmlFullPath(string strPath) { if (strPath.IndexOf(":") > 0) { return strPath; } else { return System.Web.HttpContext.Current.Server.MapPath(strPath); } } #endregion #region 讀取數據 /// <summary> /// 讀取指定節點的數據 /// </summary> /// <param name="node">節點</param> /// 使用示列: /// XMLProsess.Read("/Node", "") /// XMLProsess.Read("/Node/Element[@Attribute='Name']") public string Read(string node) { string value = ""; try { XmlDocument doc = XMLLoad(); XmlNode xn = doc.SelectSingleNode(node); value = xn.InnerText; } catch { } return value; } /// <summary> /// 讀取指定路徑和節點的串聯值 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="attribute">屬性名,非空時返回該屬性值,否則返回串聯值</param> /// 使用示列: /// XMLProsess.Read(path, "/Node", "") /// XMLProsess.Read(path, "/Node/Element[@Attribute='Name']") public static string Read(string path, string node) { string value = ""; try { XmlDocument doc = XMLLoad(path); XmlNode xn = doc.SelectSingleNode(node); value = xn.InnerText; } catch { } return value; } /// <summary> /// 讀取指定路徑和節點的屬性值 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="attribute">屬性名,非空時返回該屬性值,否則返回串聯值</param> /// 使用示列: /// XMLProsess.Read(path, "/Node", "") /// XMLProsess.Read(path, "/Node/Element[@Attribute='Name']", "Attribute") public static string Read(string path, string node, string attribute) { string value = ""; try { XmlDocument doc = XMLLoad(path); XmlNode xn = doc.SelectSingleNode(node); value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value); } catch { } return value; } /// <summary> /// 獲取某一節點的所有孩子節點的值 /// </summary> /// <param name="node">要查詢的節點</param> public string[] ReadAllChildallValue(string node) { int i = 0; string[] str = { }; XmlDocument doc = XMLLoad(); XmlNode xn = doc.SelectSingleNode(node); XmlNodeList nodelist = xn.ChildNodes; //得到該節點的子節點 if (nodelist.Count > 0) { str = new string[nodelist.Count]; foreach (XmlElement el in nodelist)//讀元素值 { str[i] = el.Value; i++; } } return str; } /// <summary> /// 獲取某一節點的所有孩子節點的值 /// </summary> /// <param name="node">要查詢的節點</param> public XmlNodeList ReadAllChild(string node) { XmlDocument doc = XMLLoad(); XmlNode xn = doc.SelectSingleNode(node); XmlNodeList nodelist = xn.ChildNodes; //得到該節點的子節點 return nodelist; } /// <summary> /// 讀取XML返回經排序或篩選後的DataView /// </summary> /// <param name="strWhere">篩選條件,如:"name='kgdiwss'"</param> /// <param name="strSort"> 排序條件,如:"Id desc"</param> public DataView GetDataViewByXml(string strWhere, string strSort) { try { string XMLFile = this.XMLPath; string filename = AppDomain.CurrentDomain.BaseDirectory.ToString() + XMLFile; DataSet ds = new DataSet(); ds.ReadXml(filename); DataView dv = new DataView(ds.Tables[0]); //創建DataView來完成排序或篩選操作 if (strSort != null) { dv.Sort = strSort; //對DataView中的記錄進行排序 } if (strWhere != null) { dv.RowFilter = strWhere; //對DataView中的記錄進行篩選,找到我們想要的記錄 } return dv; } catch (Exception) { return null; } } /// <summary> /// 讀取XML返回DataSet /// </summary> /// <param name="strXmlPath">XML文件相對路徑</param> public DataSet GetDataSetByXml(string strXmlPath) { try { DataSet ds = new DataSet(); ds.ReadXml(GetXmlFullPath(strXmlPath)); if (ds.Tables.Count > 0) { return ds; } return null; } catch (Exception) { return null; } } #endregion #region 插入數據 /// <summary> /// 插入數據 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="element">元素名,非空時插入新元素,否則在該元素中插入屬性</param> /// <param name="attribute">屬性名,非空時插入該元素屬性值,否則插入元素值</param> /// <param name="value">值</param> /// 使用示列: /// XMLProsess.Insert(path, "/Node", "Element", "", "Value") /// XMLProsess.Insert(path, "/Node", "Element", "Attribute", "Value") /// XMLProsess.Insert(path, "/Node", "", "Attribute", "Value") public static void Insert(string path, string node, string element, string attribute, string value) { try { XmlDocument doc = new XmlDocument(); doc.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + 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(AppDomain.CurrentDomain.BaseDirectory.ToString() + path); } catch { } } /// <summary> /// 插入數據 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="element">元素名,非空時插入新元素,否則在該元素中插入屬性</param> /// <param name="strList">由XML屬性名和值組成的二維數組</param> public static void Insert(string path, string node, string element, string[][] strList) { try { XmlDocument doc = new XmlDocument(); doc.Load(AppDomain.CurrentDomain.BaseDirectory.ToString() + path); XmlNode xn = doc.SelectSingleNode(node); XmlElement xe = doc.CreateElement(element); string strAttribute = ""; string strValue = ""; for (int i = 0; i < strList.Length; i++) { for (int j = 0; j < strList[i].Length; j++) { if (j == 0) strAttribute = strList[i][j]; else strValue = strList[i][j]; } if (strAttribute.Equals("")) xe.InnerText = strValue; else xe.SetAttribute(strAttribute, strValue); } xn.AppendChild(xe); doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() + path); } catch { } } /// <summary> /// 插入一行數據 /// </summary> /// <param name="strXmlPath">XML文件相對路徑</param> /// <param name="Columns">要插入行的列名數組,如:string[] Columns = {"name","IsMarried"};</param> /// <param name="ColumnValue">要插入行每列的值數組,如:string[] ColumnValue={"XML大全","false"};</param> /// <returns>成功返回true,否則返回false</returns> public static bool WriteXmlByDataSet(string strXmlPath, string[] Columns, string[] ColumnValue) { try { //根據傳入的XML路徑得到.XSD的路徑,兩個文件放在同一個目錄下 string strXsdPath = strXmlPath.Substring(0, strXmlPath.IndexOf(".")) + ".xsd"; DataSet ds = new DataSet(); ds.ReadXmlSchema(GetXmlFullPath(strXsdPath)); //讀XML架構,關係到列的數據類型 ds.ReadXml(GetXmlFullPath(strXmlPath)); DataTable dt = ds.Tables[0]; DataRow newRow = dt.NewRow(); //在原來的表格基礎上創建新行 for (int i = 0; i < Columns.Length; i++) //迴圈給一行中的各個列賦值 { newRow[Columns[i]] = ColumnValue[i]; } dt.Rows.Add(newRow); dt.AcceptChanges(); ds.AcceptChanges(); ds.WriteXml(GetXmlFullPath(strXmlPath)); return true; } catch (Exception) { return false; } } #endregion #region 修改數據 /// <summary> /// 修改指定節點的數據 /// </summary> /// <param name="node">節點</param> /// <param name="value">值</param> public void Update(string node, string value) { try { XmlDocument doc = XMLLoad(); XmlNode xn = doc.SelectSingleNode(node); xn.InnerText = value; doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() + XMLPath); } catch { } } /// <summary> /// 修改指定節點的數據 /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="value">值</param> /// 使用示列: /// XMLProsess.Insert(path, "/Node","Value") /// XMLProsess.Insert(path, "/Node","Value") public static void Update(string path, string node, string value) { try { XmlDocument doc = XMLLoad(path); XmlNode xn = doc.SelectSingleNode(node); xn.InnerText = value; doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString() + path); } catch { } } /// <summary> /// 修改指定節點的屬性值(靜態) /// </summary> /// <param name="path">路徑</param> /// <param name="node">節點</param> /// <param name="attribute">屬性名,非空時修改該節點屬性值,否則修改節點值</param> /// <param name="value">值</param> /// 使用示列: /// XMLProsess.Insert(path, "/Node", "", "Value") /// XMLProsess.Insert(path, "/Node", "Attribute", "Value") public static void Update(