寫的一個XML操作類,包括讀取/插入/修改/刪除。
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
namespace PuTianCheng
{
/// <summary>
/// XmlHelper 的摘要說明
/// </summary>
public class XmlHelper
{
public 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 static 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 static 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.A