C # XML file Operation class Xmlhelper

Source: Internet
Author: User
Tags xpath

The complete code for the class:

Using System;
Using System.Collections;
Using System.Xml;

Namespace Keleyi.Com.XmlDAL
{
public class Xmlhelper
{
#region Public variables
XmlDocument xmldoc;
XmlNode XmlNode;
XmlElement Xmlelem;
#endregion

#region Creating an XML document
<summary>
Create an XML file with the root node
</summary>
<param name= "FileName" >xml file name </param>
<param name= "Rootname" > Root node name </param>
<param name= "Encode" > Encoding method: Gb2312,utf-8 and other common </param>
<param name= "Dirpath" > Saved directory path </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 Common methods of operation (increase and deletion)
<summary>
Insert a node and several of its child nodes
</summary>
<param name= "xmlfile" >xml file path </param>
<param name= "Newnodename" > inserted node name </param>
<param name= "HasAttributes" > Whether this node has properties, true to have, false to none </param>
<param name= "Fathernode" > The parent node of this insertion node, the XPath expression to match (for example: "//Node name/child node name) </param>
<param name= "Htatt" > Properties of this node, key is the property name, value is the property value </param>
<param name= "Htsubnode" > Child node Properties, key is Name,value to innertext</param>
<returns> returns true for update success, otherwise failure </returns>
public bool Insertnode (string xmlfile, String newnodename, bool HasAttributes, String fathernode, Hashtable Htatt, Hashtab Le Htsubnode)
{
Try
{
xmldoc = new XmlDocument ();
XmlDoc. Load (xmlfile);
XmlNode root = xmldoc. selectSingleNode (Fathernode);
Xmlelem = xmldoc. CreateElement (Newnodename);
if (Htatt! = null && hasattributes)//If this node has attributes, add the property first
{
SetAttributes (Xmlelem, Htatt);
Setnodes (Xmlelem. Name, xmldoc, Xmlelem, Htsubnode);//After you add this node property, add its child nodes and their innertext
}
Else
{
Setnodes (Xmlelem. Name, xmldoc, Xmlelem, Htsubnode);//If this node has no attributes, add its child nodes directly
}

Root. AppendChild (Xmlelem);
XmlDoc. Save (xmlfile);

return true;
}
catch (Exception e)
{

throw new Exception (e.message);

}
}
<summary>
Update node
</summary>
<param name= "xmlfile" >xml file path </param>
<param name= "Fathernode" > Need to update the node's ancestor node, to match the XPath expression (for example: "//Node name/sub-node name) </param>
<param name= "Htatt" > The property sheet that needs to be updated, the key represents the property that needs to be updated, and value represents the updated value </param>
<param name= "Htsubnode" > the attribute table of the child nodes that need to be updated, key represents the child node name that needs to be updated Name,value represents the updated value innertext</param>
<returns> returns true for update success, otherwise failure </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>
Delete a child node under a specified node
</summary>
<param name= "xmlfile" >xml file path </param>
<param name= "Fathernode" > Develop nodes, XPath expressions to match (ex: "//Node name/sub-node name) </param>
<returns> returns true for update success, otherwise failure </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>
Delete the first node that matches the XPath expression (the child elements in the node are also deleted)
</summary>
<param name= "XMLfileName" >xml document full file name (contains physical path) </param>
<param name= "XPath" > XPath expression to match (for example: "//Node name//Sub-node name </param>
<returns> successful return true, failed to return false</returns>
public bool Deletexmlnodebyxpath (string xmlfilename, String XPath)
{
BOOL issuccess = false;
xmldoc = new XmlDocument ();
Try
{
XmlDoc. Load (XMLfileName); Loading an XML document
XmlNode XmlNode = xmldoc. selectSingleNode (XPath);
if (XmlNode! = null)
{
Delete a node
XmlDoc. Parentnode.removechild (XmlNode);
}
XmlDoc. Save (XMLfileName); Save to XML document
Issuccess = true;
}
catch (Exception ex)
{
Throw ex; You can define your own exception handling here.
}
return issuccess;
}

/* keleyi.com */
<summary>
Delete the property of the matching parameter Xmlattributename in the first node of the matching XPath expression
</summary>
<param name= "XMLfileName" >xml document full file name (contains physical path) </param>
<param name= "XPath" > XPath expression to match (for example: "//Node name//Sub-node name </param>
<param name= "Xmlattributename" > property name of the xmlattributename to delete </param>
<returns> successful return true, failed to return false</returns>
public bool Deletexmlattributebyxpath (string XMLfileName, String xpath, string xmlattributename)
{
BOOL issuccess = false;
BOOL Isexistsattribute = false;
xmldoc = new XmlDocument ();
Try
{
XmlDoc. Load (XMLfileName); Loading an XML document
XmlNode XmlNode = xmldoc. selectSingleNode (XPath);
XmlAttribute XmlAttribute = null;
if (XmlNode! = null)
{
Traverse all properties in an XPath node
foreach (XmlAttribute attribute in xmlnode.attributes)
{
if (attribute. Name.tolower () = = Xmlattributename.tolower ())
{
This property exists in the node
XmlAttribute = attribute;
Isexistsattribute = true;
Break
}
}
if (Isexistsattribute)
{
Delete a property in a node
XmlNode.Attributes.Remove (XmlAttribute);
}
}
XmlDoc. Save (XMLfileName); Save to XML document
Issuccess = true;
}
catch (Exception ex)
{
Throw ex; You can define your own exception handling here.
}
return issuccess;
}

/* Collayi */
<summary>
Delete all attributes in the first node that match the XPath expression
</summary>
<param name= "XMLfileName" >xml document full file name (contains physical path) </param>
<param name= "XPath" > XPath expression to match (for example: "//Node name//Sub-node name </param>
<returns> successful return true, failed to return false</returns>
public bool Deleteallxmlattributebyxpath (string xmlfilename, String XPath)
{
BOOL issuccess = false;
xmldoc = new XmlDocument ();
Try
{
XmlDoc. Load (XMLfileName); Loading an XML document
XmlNode XmlNode = xmldoc. selectSingleNode (XPath);
if (XmlNode! = null)
{
Traverse all properties in an XPath node
XmlNode.Attributes.RemoveAll ();
}
XmlDoc. Save (XMLfileName); Save to XML document
Issuccess = true;
}
catch (Exception ex)
{
Throw ex; You can define your own exception handling here.
}
return issuccess;
}
#endregion

#region Private Methods
<summary>
Set node properties
</summary>
<param name= "XE" > Node element</param>
<param name= "Htattribute" > Node properties, key for property name, value for property value </param>
private void SetAttributes (XmlElement xe, Hashtable Htattribute)
{
foreach (DictionaryEntry de in Htattribute)
{
Xe. SetAttribute (DE. Key.tostring (), DE. Value.tostring ());
}
}
<summary>
Add child nodes to the root node
</summary>
<param name= "RootNode" > Ancestor node name </param>
<param name= "xmldoc" >xml document </param>
<param name= "Rootxe" > Parent root node belongs to element</param>
<param name= "Subnodes" > Child node Properties, key is the name value, value is innertext value </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>
Update node properties and child node innertext values. Collayi
</summary>
<param name= "root" > root node name </param>
<param name= "Htatt" > property names and values that need to be changed </param>
<param name= "Htsubnode" > Need to change InnerText's child node name and value </param>
private void Updatenodes (XmlNodeList root, Hashtable Htatt, Hashtable htsubnode)
{
foreach (XmlNode xn in root)
{
Xmlelem = (XmlElement) xn;
if (Xmlelem. HasAttributes)//If the node is a property, change its properties first
{
foreach (DictionaryEntry de in Htatt)//Traversal Property Hash table
{
if (Xmlelem. Hasattribute (DE. Key.tostring ()))//If the node has properties that need to be changed
{
Xmlelem. SetAttribute (DE. Key.tostring (), DE. Value.tostring ());//The corresponding value in the hash table is assigned to this property key
}
}
}
if (Xmlelem. HasChildNodes)//If there are child nodes, modify the innertext of their child nodes
{
XmlNodeList XNL = Xmlelem. ChildNodes;
foreach (XmlNode xn1 in XNL)
{
XmlElement XE = (XmlElement) xn1;
foreach (DictionaryEntry de in Htsubnode)
{
if (XE. Name = = de. Key.tostring ()) the key in//htsubnode stores the name of the node that needs to be changed.
{
Xe. InnerText = de. Value.tostring (); value in//htsubnode stores the updated data of the key node
}
}
}
}

}
}
#endregion
Querying and reading #region XML document nodes
/**/
<summary>
Select the first node that matches the XPath expression XmlNode.
</summary>
<param name= "XMLfileName" >xml document full file name (contains physical path) </param>
<param name= "XPath" > XPath expression to match (for example: "//Node name/sub-node name") </param>
<returns> Back to Xmlnode</returns>
Public XmlNode Getxmlnodebyxpath (String xmlfilename, String XPath)
{
xmldoc = new XmlDocument ();
Try
{
XmlDoc. Load (XMLfileName); Loading an XML document
XmlNode XmlNode = xmldoc. selectSingleNode (XPath);
return xmlNode;
}
catch (Exception ex)
{
return null;
Throw ex; You can define your own exception handling here.
}
}

/**/
<summary>
Select the node list xmlnodelist that matches the XPath expression.
</summary>
<param name= "XMLfileName" >xml document full file name (contains physical path) </param>
<param name= "XPath" > XPath expression to match (for example: "//Node name/sub-node name") </param>
<returns> Back to Xmlnodelist</returns>
Public XmlNodeList Getxmlnodelistbyxpath (String xmlfilename, String XPath)
{
xmldoc = new XmlDocument ();
Try
{
XmlDoc. Load (XMLfileName); Loading an XML document
XmlNodeList XmlNodeList = xmldoc. SelectNodes (XPath);
return xmlnodelist;
}
catch (Exception ex)
{
return null;
Throw ex; You can define your own exception handling here.
}
}

/**/
<summary>
Select the Match Xmlattributename property XmlAttribute that matches the first node of the XPath expression. Collayi
</summary>
<param name= "XMLfileName" >xml document full file name (contains physical path) </param>
<param name= "XPath" > XPath expression to match (for example: "//Node name//Sub-node name </param>
<param name= "Xmlattributename" > property name to match Xmlattributename </param>
<returns> Back to 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); Loading an XML document
XmlNode XmlNode = xmldoc. selectSingleNode (XPath);
if (XmlNode! = null)
{
if (XmlNode.Attributes.Count > 0)
{
XmlAttribute = Xmlnode.attributes[xmlattributename];
}
}
}
catch (Exception ex)
{
Throw ex; You can define your own exception handling here.
}
return XmlAttribute;
}
#endregion
}
}



How does this class work? An example of creating an XML document is given below:
Xmlhelper m_menu_keleyi_com = new Xmlhelper ();
M_menu_keleyi_com. Createxmldocument (@ "D:\kel" + "Eyimenu.xml", "Ke" + "Leyimenu", "utf-8");

This short code creates a document named Keleyimenu.xml in the D-disk with the root node Keleyimenu and the contents of the document as:
<?xml version= "1.0" encoding= "Utf-8"?>
<keleyimenu/>

This article adds nodes to the XML document that was created in the previous article.

The code is as follows:

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);

Of course you need to refer to namespaces:
Using Keleyi.Com.XmlDAL;

The contents of the resulting XML file Keleyimenu.xml are:

<?xml version= "1.0" encoding= "Utf-8"?>
<keleyimenu>
<csharp text= "C #" url= "http://keleyi.com/menu/csharp/"/>
</keleyimenu>

The previous article has been added under the root node CSharp, now to get the node, already the node's property values.

The code is as follows:

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;

So now the value of M_nodetext is C #
And the value of M_nodeurl is: http://keleyi.com/menu/csharp/

C # XML file Operation class Xmlhelper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.