Write an XML operation class, including reading, inserting, modifying, and deleting.
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>
/// Summary of XmlHelper
/// </Summary>
Public class XmlHelper
{
Public XmlHelper ()
{
}
/// <Summary>
/// Read data
/// </Summary>
/// <Param name = "path"> path </param>
/// <Param name = "node"> node </param>
/// <Param name = "attribute"> attribute name. This attribute value is returned if it is not null. Otherwise, a series value is returned. </param>
/// <Returns> string </returns>
/*************************************** ***********
* Use the display column:
* 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>
/// Insert data
/// </Summary>
/// <Param name = "path"> path </param>
/// <Param name = "node"> node </param>
/// <Param name = "element"> element name. If it is not null, a new element is inserted. Otherwise, an attribute is inserted into the element. </param>
/// <Param name = "attribute"> attribute name. If it is not null, the attribute value of this element is inserted. Otherwise, the element value is inserted. </param>
/// <Param name = "value"> value </param>
/// <Returns> </returns>
/*************************************** ***********
* Use the display column:
* 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.