標籤:
類的完整代碼:
using System;
using System.Collections;
using System.Xml;
namespace Keleyi.Com.XmlDAL
{
public class XmlHelper
{
#region 公開變數
XmlDocument xmldoc;
XmlNode xmlnode;
XmlElement xmlelem;
#endregion
#region 建立Xml文檔
/// <summary>
/// 建立一個帶有根節點的Xml檔案
/// </summary>
/// <param name="FileName">Xml檔案名稱</param>
/// <param name="rootName">根節點名稱</param>
/// <param name="Encode">編碼方式:gb2312,UTF-8等常見的</param>
/// <param name="DirPath">儲存的目錄路徑</param>
/// <returns></returns>
public bool CreateXmlDocument(string FileName, string RootName, string Encode)
{
try
{
xmldoc = new XmlDocument();
XmlDeclaration xmldecl;
xmldecl = xmldoc.CreateXmlDeclaration("1.0", Encode,null);
xmldoc.AppendChild(xmldecl);
xmlelem = xmldoc.CreateElement("", RootName, "");
xmldoc.AppendChild(xmlelem);
xmldoc.Save(FileName);
return true;
}
catch (Exception e)
{
return false;
throw new Exception(e.Message);
}
}
#endregion
#region 常用操作方法(增刪改)
/// <summary>
/// 插入一個節點和它的若干子節點
/// </summary>
/// <param name="XmlFile">Xml檔案路徑</param>
/// <param name="NewNodeName">插入的節點名稱</param>
/// <param name="HasAttributes">此節點是否具有屬性,True為有,False為無</param>
/// <param name="fatherNode">此插入節點的父節點,要匹配的XPath運算式(例如:"//節點名//子節點名)</param>
/// <param name="htAtt">此節點的屬性,Key為屬性名稱,Value為屬性值</param>
/// <param name="htSubNode">子節點的屬性,Key為Name,Value為InnerText</param>
/// <returns>返回真為更新成功,否則失敗</returns>
public bool InsertNode(string XmlFile, string NewNodeName, bool HasAttributes, string fatherNode, Hashtable htAtt, Hashtable htSubNode)
{
try
{
xmldoc = new XmlDocument();
xmldoc.Load(XmlFile);
XmlNode root = xmldoc.SelectSingleNode(fatherNode);
xmlelem = xmldoc.CreateElement(NewNodeName);
if (htAtt != null && HasAttributes)//若此節點有屬性,則先添加屬性
{
SetAttributes(xmlelem, htAtt);
SetNodes(xmlelem.Name, xmldoc, xmlelem, htSubNode);//添加完此節點屬性後,再添加它的子節點和它們的InnerText
}
else
{
SetNodes(xmlelem.Name, xmldoc, xmlelem, htSubNode);//若此節點無屬性,那麼直接添加它的子節點
}
root.AppendChild(xmlelem);
xmldoc.Save(XmlFile);
return true;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 更新節點
/// </summary>
/// <param name="XmlFile">Xml檔案路徑</param>
/// <param name="fatherNode">需要更新節點的上級節點,要匹配的XPath運算式(例如:"//節點名//子節點名)</param>
/// <param name="htAtt">需要更新的屬性工作表,Key代表需要更新的屬性,Value代表更新後的值</param>
/// <param name="htSubNode">需要更新的子節點的屬性工作表,Key代表需要更新的子節點名字Name,Value代表更新後的值InnerText</param>
/// <returns>返回真為更新成功,否則失敗</returns>
public bool UpdateNode(string XmlFile, string fatherNode, Hashtable htAtt, Hashtable htSubNode)
{
try
{
xmldoc = new XmlDocument();
xmldoc.Load(XmlFile);
XmlNodeList root = xmldoc.SelectSingleNode(fatherNode).ChildNodes;
UpdateNodes(root, htAtt, htSubNode);
xmldoc.Save(XmlFile);
return true;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
/// <summary>
/// 刪除指定節點下的子節點
/// </summary>
/// <param name="XmlFile">Xml檔案路徑</param>
/// <param name="fatherNode">制定節點,要匹配的XPath運算式(例如:"//節點名//子節點名)</param>
/// <returns>返回真為更新成功,否則失敗</returns>
public bool DeleteNodes(string XmlFile, string fatherNode)
{
try
{
xmldoc = new XmlDocument();
xmldoc.Load(XmlFile);
xmlnode = xmldoc.SelectSingleNode(fatherNode);
xmlnode.RemoveAll();
xmldoc.Save(XmlFile);
return true;
}
catch (XmlException xe)
{
throw new XmlException(xe.Message);
}
}
/*keleyi*/
/// <summary>
/// 刪除匹配XPath運算式的第一個節點(節點中的子項目同時會被刪除)
/// </summary>
/// <param name="xmlFileName">XML文檔完全檔案名稱(包含實體路徑)</param>
/// <param name="xpath">要匹配的XPath運算式(例如:"//節點名//子節點名</param>
/// <returns>成功返回true,失敗返回false</returns>
public bool DeleteXmlNodeByXPath(string xmlFileName, string xpath)
{
bool isSuccess = false;
xmldoc = new XmlDocument();
try
{
xmldoc.Load(xmlFileName); //載入XML文檔
XmlNode xmlNode = xmldoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//刪除節點
xmldoc.ParentNode.RemoveChild(xmlNode);
}
xmldoc.Save(xmlFileName); //儲存到XML文檔
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //這裡可以定義你自己的異常處理
}
return isSuccess;
}
/* keleyi.com */
/// <summary>
/// 刪除匹配XPath運算式的第一個節點中的匹配參數xmlAttributeName的屬性
/// </summary>
/// <param name="xmlFileName">XML文檔完全檔案名稱(包含實體路徑)</param>
/// <param name="xpath">要匹配的XPath運算式(例如:"//節點名//子節點名</param>
/// <param name="xmlAttributeName">要刪除的xmlAttributeName的屬性名稱</param>
/// <returns>成功返回true,失敗返回false</returns>
public bool DeleteXmlAttributeByXPath(string xmlFileName, string xpath, string xmlAttributeName)
{
bool isSuccess = false;
bool isExistsAttribute = false;
xmldoc = new XmlDocument();
try
{
xmldoc.Load(xmlFileName); //載入XML文檔
XmlNode xmlNode = xmldoc.SelectSingleNode(xpath);
XmlAttribute xmlAttribute = null;
if (xmlNode != null)
{
//遍曆xpath節點中的所有屬性
foreach (XmlAttribute attribute in xmlNode.Attributes)
{
if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
{
//節點中存在此屬性
xmlAttribute = attribute;
isExistsAttribute = true;
break;
}
}
if (isExistsAttribute)
{
//刪除節點中的屬性
xmlNode.Attributes.Remove(xmlAttribute);
}
}
xmldoc.Save(xmlFileName); //儲存到XML文檔
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //這裡可以定義你自己的異常處理
}
return isSuccess;
}
/*柯樂義*/
/// <summary>
/// 刪除匹配XPath運算式的第一個節點中的所有屬性
/// </summary>
/// <param name="xmlFileName">XML文檔完全檔案名稱(包含實體路徑)</param>
/// <param name="xpath">要匹配的XPath運算式(例如:"//節點名//子節點名</param>
/// <returns>成功返回true,失敗返回false</returns>
public bool DeleteAllXmlAttributeByXPath(string xmlFileName, string xpath)
{
bool isSuccess = false;
xmldoc = new XmlDocument();
try
{
xmldoc.Load(xmlFileName); //載入XML文檔
XmlNode xmlNode = xmldoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//遍曆xpath節點中的所有屬性
xmlNode.Attributes.RemoveAll();
}
xmldoc.Save(xmlFileName); //儲存到XML文檔
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //這裡可以定義你自己的異常處理
}
return isSuccess;
}
#endregion
#region 私人方法
/// <summary>
/// 設定節點屬性
/// </summary>
/// <param name="xe">節點所處的Element</param>
/// <param name="htAttribute">節點屬性,Key代表屬性名稱,Value代表屬性值</param>
private void SetAttributes(XmlElement xe, Hashtable htAttribute)
{
foreach (DictionaryEntry de in htAttribute)
{
xe.SetAttribute(de.Key.ToString(), de.Value.ToString());
}
}
/// <summary>
/// 增加子節點到根節點下
/// </summary>
/// <param name="rootNode">上級節點名稱</param>
/// <param name="XmlDoc">Xml文檔</param>
/// <param name="rootXe">父根節點所屬的Element</param>
/// <param name="SubNodes">子節點屬性,Key為Name值,Value為InnerText值</param>
private void SetNodes(string rootNode, XmlDocument XmlDoc, XmlElement rootXe, Hashtable SubNodes)
{
if (SubNodes == null)
return;
foreach (DictionaryEntry de in SubNodes)
{
xmlnode = XmlDoc.SelectSingleNode(rootNode);
XmlElement subNode = XmlDoc.CreateElement(de.Key.ToString());
subNode.InnerText = de.Value.ToString();
rootXe.AppendChild(subNode);
}
}
/// <summary>
/// 更新節點屬性和子節點InnerText值。柯 樂 義
/// </summary>
/// <param name="root">根節點名字</param>
/// <param name="htAtt">需要更改的屬性名稱和值</param>
/// <param name="htSubNode">需要更改InnerText的子節點名字和值</param>
private void UpdateNodes(XmlNodeList root, Hashtable htAtt, Hashtable htSubNode)
{
foreach (XmlNode xn in root)
{
xmlelem = (XmlElement)xn;
if (xmlelem.HasAttributes)//如果節點如屬性,則先更改它的屬性
{
foreach (DictionaryEntry de in htAtt)//遍曆屬性雜湊表
{
if (xmlelem.HasAttribute(de.Key.ToString()))//如果節點有需要更改的屬性
{
xmlelem.SetAttribute(de.Key.ToString(), de.Value.ToString());//則把雜湊表中相應的值Value賦給此屬性Key
}
}
}
if (xmlelem.HasChildNodes)//如果有子節點,則修改其子節點的InnerText
{
XmlNodeList xnl = xmlelem.ChildNodes;
foreach (XmlNode xn1 in xnl)
{
XmlElement xe = (XmlElement)xn1;
foreach (DictionaryEntry de in htSubNode)
{
if (xe.Name == de.Key.ToString())//htSubNode中的key儲存了需要更改的節點名稱,
{
xe.InnerText = de.Value.ToString();//htSubNode中的Value儲存了Key節點更新後的資料
}
}
}
}
}
}
#endregion
#region XML文檔節點查詢和讀取
/**/
/// <summary>
/// 選擇匹配XPath運算式的第一個節點XmlNode.
/// </summary>
/// <param name="xmlFileName">XML文檔完全檔案名稱(包含實體路徑)</param>
/// <param name="xpath">要匹配的XPath運算式(例如:"//節點名//子節點名")</param>
/// <returns>返回XmlNode</returns>
public XmlNode GetXmlNodeByXpath(string xmlFileName, string xpath)
{
xmldoc = new XmlDocument();
try
{
xmldoc.Load(xmlFileName); //載入XML文檔
XmlNode xmlNode = xmldoc.SelectSingleNode(xpath);
return xmlNode;
}
catch (Exception ex)
{
return null;
//throw ex; //這裡可以定義你自己的異常處理
}
}
/**/
/// <summary>
/// 選擇匹配XPath運算式的節點列表XmlNodeList.
/// </summary>
/// <param name="xmlFileName">XML文檔完全檔案名稱(包含實體路徑)</param>
/// <param name="xpath">要匹配的XPath運算式(例如:"//節點名//子節點名")</param>
/// <returns>返回XmlNodeList</returns>
public XmlNodeList GetXmlNodeListByXpath(string xmlFileName, string xpath)
{
xmldoc = new XmlDocument();
try
{
xmldoc.Load(xmlFileName); //載入XML文檔
XmlNodeList xmlNodeList = xmldoc.SelectNodes(xpath);
return xmlNodeList;
}
catch (Exception ex)
{
return null;
//throw ex; //這裡可以定義你自己的異常處理
}
}
/**/
/// <summary>
/// 選擇匹配XPath運算式的第一個節點的匹配xmlAttributeName的屬性XmlAttribute. 柯樂義
/// </summary>
/// <param name="xmlFileName">XML文檔完全檔案名稱(包含實體路徑)</param>
/// <param name="xpath">要匹配的XPath運算式(例如:"//節點名//子節點名</param>
/// <param name="xmlAttributeName">要匹配xmlAttributeName的屬性名稱</param>
/// <returns>返回xmlAttributeName</returns>
public XmlAttribute GetXmlAttribute(string xmlFileName, string xpath, string xmlAttributeName)
{
string content = string.Empty;
xmldoc = new XmlDocument();
XmlAttribute xmlAttribute = null;
try
{
xmldoc.Load(xmlFileName); //載入XML文檔
XmlNode xmlNode = xmldoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
if (xmlNode.Attributes.Count > 0)
{
xmlAttribute = xmlNode.Attributes[xmlAttributeName];
}
}
}
catch (Exception ex)
{
throw ex; //這裡可以定義你自己的異常處理
}
return xmlAttribute;
}
#endregion
}
}
這個類怎麼使用呢?下面給出一個建立xml文檔的例子:
XmlHelper m_menu_keleyi_com = new XmlHelper();
m_menu_keleyi_com.CreateXmlDocument(@"D:\kel"+"eyimenu.xml", "ke"+"leyimenu", "utf-8");
這短代碼在D盤建立了一個名為keleyimenu.xml的文檔,文檔有根節點keleyimenu,文檔的內容為:
<?xml version="1.0" encoding="utf-8"?>
<keleyimenu />
本篇則在上篇建立的xml文檔中增加了節點。
代碼如下:
XmlHelper m_menu_keleyi_com = new XmlHelper();
Hashtable m_ht = new Hashtable();
m_ht.Add("url", "http://keleyi.com/menu/csharp/");
m_ht.Add("text", "C#");
return m_menu_keleyi_com.InsertNode(@"D:\kel" + "eyimenu.xml", "csharp", true, "keleyimenu", m_ht, null);
當然需要引用命名空間:
using Keleyi.Com.XmlDAL;
結果xml檔案keleyimenu.xml的內容為:
<?xml version="1.0" encoding="utf-8"?>
<keleyimenu>
<csharp text="C#" url="http://keleyi.com/menu/csharp/" />
</keleyimenu>
上一篇已經在根節點下添加了節點csharp,現在來擷取該節點,已經該節點的屬性值。
代碼如下:
string m_nodeName = "csharp";
XmlNode m_menuNode_keleyi_com = m_menu_keleyi_com.GetXmlNodeByXpath(@"D:\kel" + "eyimenu.xml", "//kele"+"yimenu//"+m_nodeName);
string m_nodeText = m_menuNode_keleyi_com.Attributes["text"].Value;
string m_nodeUrl = m_menuNode_keleyi_com.Attributes["url"].Value;
那麼現在m_nodeText的值為c#
而m_nodeUrl的值為:http://keleyi.com/menu/csharp/
C# XML檔案操作類XmlHelper