The complete code of the C # XML file operation class Xmlhelper class

Source: Internet
Author: User
Tags exception handling xpath

The complete code for the C # XML file Operation class Xmlhelper class:

Using System;

Using System.Collections;

Using System.Xml;

Namespace Com.xmldal

{

public class Xmlhelper

{

#region Public variables

XmlDocument xmldoc;

XmlNode XmlNode;

XmlElement Xmlelem;

#endregion

#region Create an XML document

<summary>

Create an XML file with a root node

</summary>

<paramname= "FileName" >xml file name </param>

<paramname= "Rootname" > Root node name </param>

<paramname= "Encode" > Encoding mode: Gb2312,utf-8 and other common </param>

<paramname= "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 newexception (E.message);

}

}

#endregion

#region Common methods of operation (add to the deletion)

<summary>

Insert a node and several of its child nodes

</summary>

<paramname= "XmlFile" >xml file path </param>

<paramname= "Newnodename" > inserted node name </param>

<paramname= "HasAttributes" > Whether this node has attributes, true to have, false to no </param>

<paramname= "Fathernode" > The parent node of this insertion node, the XPath expression to match (for example: "//section name//Sub-section name) </param>

<paramname= "Htatt" > This node's properties, key is the property name, value is the property value </param>

<paramname= "Htsubnode" > Child node Properties, key is Name,value to innertext</param>

<returns> return True for update success or failure </returns>

Public bool Insertnode (string XmlFile, String newnodename, Boolhasattributes, String fathernode, Hashtable Htatt, has Htable 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 adding this node property, add its child nodes and their innertext

}

Else

{

Setnodes (Xmlelem. Name,xmldoc, Xmlelem, Htsubnode)//If this node has no attributes, then add its child nodes directly

}

Root. AppendChild (Xmlelem);

XmlDoc. Save (XmlFile);

return true;

}

catch (Exception e)

{

Throw newexception (E.message);

}

}

<summary>

Update node

</summary>

<paramname= "XmlFile" >xml file path </param>

<paramname= "Fathernode" > Need to update the parent node of the node, the XPath expression to match (for example: "//Node naming//Sub-section name) </param>

<paramname= "Htatt" > The property sheet that needs to be updated, the key represents the property that needs to be updated, and value represents the updated values </param>

<param name= "Htsubnode" > The property sheet for the child node that needs to be updated, the key represents the name of the child node that needs to be updated Name,value represents the updated value innertext</param>

<returns> return True for update success or 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 newexception (E.message);

}

}

<summary>

To delete a child node under a specified node

</summary>

<paramname= "XmlFile" >xml file path </param>

<paramname= "Fathernode" > Set up Nodes, XPath expressions to match (e.g.: "//Node naming//Sub-section name) </param>

<returns> return True for update success or failure </returns>

Public Booldeletenodes (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 Newxmlexception (XE. message);

}

}

/*keleyi*/

<summary>

Deletes the first node that matches an XPath expression (the child elements in the node are deleted at the same time)

</summary>

<paramname= "XMLfileName" >xml document full file name (including physical path) </param>

<paramname= "XPath" > XPath expression to match (for example: "//Node naming//Sub-section name </param>

<returns> returns true successfully, Failure returns false</returns>

Public bool Deletexmlnodebyxpath (string xmlfilename, Stringxpath)

{

BOOL issuccess = false;

xmldoc = new XmlDocument ();

Try

{

XmlDoc. Load (XMLfileName); Load 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;

}

<summary>

Deletes the properties of the matching parameter Xmlattributename in the first node of the matching XPath expression

</summary>

<paramname= "XMLfileName" >xml document full file name (including physical path) </param>

<paramname= "XPath" > XPath expression to match (for example: "//Node naming//Sub-section name </param>

<paramname= "Xmlattributename" > property name of the Xmlattributename to be deleted </param>

<returns> returns true successfully, Failure returns false</returns>

Public bool Deletexmlattributebyxpath (String XMLfileName, Stringxpath, string xmlattributename)

{

BOOL issuccess = false;

BOOL Isexistsattribute =false;

xmldoc = new XmlDocument ();

Try

{

XmlDoc. Load (XMLfileName); Load XML document

XmlNode XmlNode =xmldoc. selectSingleNode (XPath);

XmlAttribute XmlAttribute =null;

if (XmlNode!= null)

{

Traversing all the properties in an XPath node

foreach (XmlAttribute attributein xmlnode.attributes)

{

if (attribute. Name.tolower () = = Xmlattributename.tolower ())

{

This property exists in the node

XmlAttribute = attribute;

Isexistsattribute = true;

Break

}

}

if (Isexistsattribute)

{

Delete a property from 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;

}

<summary>

Deletes all properties in the first node of a matching XPath expression

</summary>

<paramname= "XMLfileName" >xml document full file name (including physical path) </param>

<param name= "XPath" > XPath expression to match (for example: "//Node naming//Sub-section name </param>

<returns> returns true successfully, Failure returns false</returns>

Public bool Deleteallxmlattributebyxpath (String xmlfilename,string XPath)

{

BOOL issuccess = false;

xmldoc = new XmlDocument ();

Try

{

XmlDoc. Load (XMLfileName); Load XML document

XmlNode XmlNode =xmldoc. selectSingleNode (XPath);

if (XmlNode!= null)

{

Traversing all the 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 Method

<summary>

Set node properties

</summary>

<paramname= "XE" > Node element</param>

<paramname= "Htattribute" > Node properties, key represents property name, value represents property value </param>

private void SetAttributes (XmlElement xe, Hashtable Htattribute)

{

foreach (DictionaryEntry dein Htattribute)

{

Xe. SetAttribute (DE. Key.tostring (), DE. Value.tostring ());

}

}

<summary>

To increase the child nodes under the root node

</summary>

<paramname= "RootNode" > Parent node name </param>

<paramname= "xmldoc" >xml document </param>

<paramname= "Rootxe" > Parent root node element</param>

<paramname= "Subnodes" > Child node Properties, key is name value, value is innertext </param>

private void Setnodes (String rootnode, XmlDocument xmldoc,xmlelement Rootxe, Hashtable subnodes)

{

if (subnodes = null)

Return

foreach (DictionaryEntry dein 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.

</summary>

<paramname= "root" > root node name </param>

<paramname= "Htatt" > property names and values that need to be changed </param>

<paramname= "Htsubnode" > Need to change the name and value of the InnerText's child node </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 like a property, change its properties first

{

foreach (dictionaryentry dein 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 ())//assigns the corresponding value in the hash table to this property key

}

}

}

if (Xmlelem. HasChildNodes)//If there is a child node, modify the innertext of its child nodes

{

XmlNodeList xnl =xmlelem. ChildNodes;

foreach (XmlNode xn1 in XNL)

{

XmlElement XE = (XmlElement) xn1;

foreach (DictionaryEntry dein Htsubnode)

{

if (XE. Name ==de. The key in the Key.tostring ())//htsubnode stores the name of the node that needs to be changed.

{

Xe. InnerText =de. Value.tostring (); value in//htsubnode stores the data after the key node has been updated

}

}

}

}

}

}

#endregion

Querying and reading #region XML document nodes

/**/

<summary>

Selects the first node XmlNode that matches an XPath expression.

</summary>

<param name= "XMLfileName" >xml document full file name (including physical path) </param>

<paramname= "XPath" > XPath expression to match (for example, "//Node name//Sub-section name") </param>

<returns> return to Xmlnode</returns>

Public XmlNode Getxmlnodebyxpath (String xmlfilename, Stringxpath)

{

xmldoc = new XmlDocument ();

Try

{

XmlDoc. Load (XMLfileName); Load 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>

<paramname= "XMLfileName" >xml document full file name (including physical path) </param>

<paramname= "XPath" > XPath expression to match (for example, "//Node name//Sub-section name") </param>

<returns> return to Xmlnodelist</returns>

Public XmlNodeList Getxmlnodelistbyxpath (String xmlfilename,string XPath)

{

xmldoc = new XmlDocument ();

Try

{

XmlDoc. Load (XMLfileName); Load 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 property XmlAttribute of the matching xmlattributename of the first node that matches the XPath expression. </summary>

<paramname= "XMLfileName" >xml document full file name (including physical path) </param>

<paramname= "XPath" > XPath expression to match (for example: "//Node naming//Sub-section name </param>

<paramname= "Xmlattributename" > property name to match Xmlattributename </param>

<returns> return to Xmlattributename</returns>

Public XmlAttribute Getxmlattribute (String xmlfilename, Stringxpath, string xmlattributename)

{

String Content =string. Empty;

xmldoc = new XmlDocument ();

XmlAttribute XmlAttribute =null;

Try

{

XmlDoc. Load (XMLfileName); Load 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 to use this class. An example of creating an XML document is given below:

Xmlhelper m_menu__com = Newxmlhelper ();

M_menu_com. Createxmldocument (@ "d:\" + "Menu.xml", "menu", "Utf-8");

This short code creates a document named Menu.xml in D disk with the root node menu, and the contents of the document are:

<?xmlversion= "1.0" encoding= "Utf-8"?>

<menu/>

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.