SoFunction
Updated on 2025-03-07

Write a simple class library for operating XML based on C# XMLHelper

I wrote an operation in the afternoonXMLThe file class library is not used later, so I can save a file for the water article

Overall function

Mainly provide the following functions:

  • Load XML file: Load the XML document from the file path or string and returnXmlDocumentObject.
  • Save XML file: Save the XmlDocument object as an XML file.
  • Read XML file toDataTable: Read data from XML file toDataTablein object.
  • Generate XML file: Generate a new XML file and specify the root node name.
  • fromDataTableUpdate XML file:DataTableThe data in the object is updated to the XML file.
  • Get node value: Get the value of the specified node according to the XPath expression.
  • Set node value: Set the value of the specified node according to the XPath expression.
  • Get attribute value: Get the attribute value of the specified node based on the XPath expression and attribute name.
  • Set attribute value: Set the attribute value of the specified node according to the XPath expression and attribute name.
  • Update node values ​​in file: Update node values ​​in XML files based on file path, XPath expression, and value.
  • Update attribute values ​​in a file: Update attribute values ​​in an XML file based on file path, XPath expression, attribute name, and value.

UselessLINQ To XMLSyntactic sugar

using System;
using ;
using ;
namespace XMLHelper
{
    class XMLHelper
    {
        private XmlDocument xmlDoc;
        public XMLHelper()
        {
            xmlDoc = new XmlDocument();
        }
        // Load the XML document from the file path or string and return the XmlDocument object        public XmlDocument LoadXmlDocumentFromFile(string filePath)
        {
            try
            {
                (filePath);
                return xmlDoc;
            }
            catch (Exception ex)
            {
                ("Error loading XML document from file: " + );
                return null;
            }
        }
        // Load the XML document from an XML string and return the XmlDocument object        public XmlDocument LoadXmlDocumentFromString(string xmlString)
        {
            try
            {
                (xmlString);
                return xmlDoc;
            }
            catch (Exception ex)
            {
                ("Error loading XML document from string: " + );
                return null;
            }
        }
        // Save XML file: Save the XmlDocument object as an XML file        public void SaveXmlDocument(XmlDocument xmlDoc, string filePath)
        {
            try
            {
                (filePath);
            }
            catch (Exception ex)
            {
                ("Error saving XML document: " + );
            }
        }
        // Generate a new XML file and specify the root node name        public void GenerateXmlFile(string filePath, string rootElementName)
        {
            try
            {
                xmlDoc = new XmlDocument();
                XmlDeclaration xmlDeclaration = ("1.0", "UTF-8", null);
                XmlNode rootNode = (rootElementName);
                (xmlDeclaration);
                (rootNode);
                (filePath);
            }
            catch (Exception ex)
            {
                ("Error generating XML file: " + );
            }
        }
        /// <summary>
        /// Read XML file to DataTable: Read data from XML file to DataTable object        /// </summary>
        /// <param name="xmlDoc">XmlDocument object</param>        /// <param name="xpath">XPath expression for node collection - for example "/Roots/Child"</param>        /// <returns>DataTable object</returns>        public DataTable ReadXmlToDataTable(XmlDocument xmlDoc,string xpath)
        {
            try
            {
                DataTable dataTable = new DataTable();
                XmlNodeList nodes = (xpath);
                foreach (XmlNode node in nodes)
                {
                    if ( == 0)
                    {
                        foreach (XmlNode childNode in )
                        {
                            (, typeof(string));
                        }
                    }
                    DataRow row = ();
                    foreach (XmlNode childNode in )
                    {
                        row[] = ;
                    }
                    (row);
                }
                return dataTable;
            }
            catch (Exception ex)
            {
                ("Error reading XML document to DataTable: " + );
                return null;
            }
        }
        /// &lt;summary&gt;
        /// Update data in DataTable object to XML file        /// &lt;/summary&gt;
        /// <param name="xmlDoc">XmlDocument object</param>        /// <param name="dataTable">DataTable object</param>        /// <param name="elementName">Child node value</param>        public void UpdateXmlFromDataTable(XmlDocument xmlDoc, DataTable dataTable,string elementName)
        {
            try
            {
                ();
                foreach (DataRow row in )
                {
                    XmlElement measurementPointElement = (elementName);
                    foreach (DataColumn column in )
                    {
                        XmlElement element = ();
                         = row[].ToString();
                        (element);
                    }
                    (measurementPointElement);
                }
            }
            catch (Exception ex)
            {
                ("Error updating XML from DataTable: " + );
            }
        }
        // Get the value of the specified node according to the XPath expression        public string GetNodeValue(XmlDocument xmlDoc, string xpath)
        {
            XmlNode node = (xpath);
            return node?.InnerText;
        }
        // Set the value of the specified node according to the XPath expression        public void SetNodeValue(XmlDocument xmlDoc, string xpath, string value)
        {
            XmlNode node = (xpath);
            if (node != null)
                 = value;
        }
        // Get the attribute value of the specified node based on the XPath expression and attribute name        public string GetAttributeValue(XmlDocument xmlDoc, string xpath, string attributeName)
        {
            XmlNode node = (xpath);
            if (node != null &amp;&amp;  != null)
            {
                XmlAttribute attribute = [attributeName];
                return attribute?.Value;
            }
            return null;
        }
        // Set the attribute value of the specified node according to the XPath expression and attribute name        public void SetAttributeValue(XmlDocument xmlDoc, string xpath, string attributeName, string value)
        {
            XmlNode node = (xpath);
            if (node != null &amp;&amp;  != null)
            {
                XmlAttribute attribute = [attributeName];
                if (attribute != null)
                     = value;
            }
        }
        // Update node values ​​in XML file according to file path, XPath expression and value        public void UpdateNodeValueInFile(string filePath, string xpath, string value)
        {
            XmlDocument doc = LoadXmlDocumentFromFile(filePath);
            if (doc != null)
            {
                SetNodeValue(doc, xpath, value);
                SaveXmlDocument(doc, filePath);
            }
        }
        // Update attribute values ​​in XML file based on file path, XPath expression, attribute name and value        public void UpdateAttributeValueInFile(string filePath, string xpath, string attributeName, string value)
        {
            XmlDocument doc = LoadXmlDocumentFromFile(filePath);
            if (doc != null)
            {
                SetAttributeValue(doc, xpath, attributeName, value);
                SaveXmlDocument(doc, filePath);
            }
        }
    }
}

Exception handling requires everyone to play freely

Loading and saving XML files

XMLHelperThe class library provides two methods for loading an XML document from a file path or string and returningXmlDocumentObjects are:

public XmlDocument LoadXmlDocumentFromFile(string filePath)
public XmlDocument LoadXmlDocumentFromString(string xmlString)

These methods can be used to load XML files intoXmlDocumentIn the object, it is convenient for subsequent processing and operations, one operates file, and one operates XML structure string, and then saves:

public void SaveXmlDocument(XmlDocument xmlDoc, string filePath)

These are all direct methods that call, and there is nothing to say.

Read and update XML files

XMLHelperClass libraries make it very easy to read data from XML files. in,ReadXmlToDataTableMethod allows data from XML files to be read toDataTableIn the object:

public DataTable ReadXmlToDataTable(XmlDocument xmlDoc, string xpath)

Just provideXmlDocumentObject and node collectionXPathExpressions (e.g."/Roots/Child") can read the data in the XML file toDataTablein object.

In addition, you can useUpdateXmlFromDataTableMethod willDataTableUpdate data in the object to the XML file:

public void UpdateXmlFromDataTable(XmlDocument xmlDoc, DataTable dataTable, string elementName)

This method will clear the XML file and followDataTableData in the object creates a new XML node and adds it toXmlDocumentin object.

Example usage

// Create XMLHelper objectXMLHelper xmlHelper = new XMLHelper();
// Load XML fileXmlDocument xmlDoc = ("");
// Read XML data to DataTableDataTable dataTable = (xmlDoc, "/Root/Element");
// Modify the value of the node[0]["Value"] = "New Value";
// Update XML file(xmlDoc, dataTable, "Element");
// Save XML file(xmlDoc, "");

Read and update the value of an XML node

XMLHelperThere are also methods for reading and updating the values ​​of XML nodes. Here are some examples of several methods:

string GetNodeValue(XmlDocument xmlDoc, string xpath)
public void SetNodeValue(XmlDocument xmlDoc, string xpath, string value)
public string GetAttributeValue(XmlDocument xmlDoc, string xpath, string attributeName)
public void SetAttributeValue(XmlDocument xmlDoc, string xpath, string attributeName, string value)

These methods allow you toXPathAn expression takes the text value or attribute value of a node and can update the text value or attribute value of a node.

Example usage

// Create XMLHelper objectXMLHelper xmlHelper = new XMLHelper();
// Load XML fileXmlDocument xmlDoc = ("");
// Read the value of the nodestring nodeValue = (xmlDoc, "/Root/Element/Value");
("Node Value: " + nodeValue);
// Update the node's valuestring newValue = "New Value";
(xmlDoc, "/Root/Element/Value", newValue);
("Node Value updated.");
// Save XML file(xmlDoc, "");

Generate XML files

In addition to loading, reading, and updating XML files, the XMLHelper class library also provides a method for generating XML files. You can useGenerateXmlFileMethod creates an empty XML file, specifying the name and file path of the root element:

public void GenerateXmlFile(string filePath, string rootElementName)

This is a bit flawed, and you will change it later.

Design ideas

ChatGPT did this :

LoadXmlDocumentFromFile(string filePath): XmlDocument

  • Function: Load XML document from the specified file path.
  • Enter: File path.
  • Output: Return the XmlDocument object after successful loading, and return null if loading failed.
  • Design idea: using XmlDocumentLoadThe method loads the XML document from the file path, and returns null if it fails.

LoadXmlDocumentFromString(string xmlString): XmlDocument

  • Function: Load XML document from the specified string.
  • Input: XML string.
  • Output: Return the XmlDocument object after successful loading, and return null if loading failed.
  • Design idea: using XmlDocumentLoadXmlMethod loads XML document from string, if loading fails, returns null.

GenerateXmlFile(string filePath, string rootElementName): void

  • Function: Generate a new XML file and specify the root node name.
  • Enter: file path, root node name.
  • Output: None.
  • Design idea: Create a new XmlDocument object and create a root node using the specified root node name. Then use XmlDocumentSaveMethod saves the XmlDocument object as an XML file with the specified file path.

SaveXmlDocument(XmlDocument xmlDoc, string filePath): void

  • Function: Save the XmlDocument object as an XML file.
  • Enter: XmlDocument object, file path.
  • Output: None.
  • Design idea: using XmlDocumentSaveMethod saves the XmlDocument object as an XML file with the specified file path.

ReadXmlToDataTable(XmlDocument xmlDoc): DataTable

  • Function: Read data from XML files into DataTable objects.
  • Enter: XmlDocument object.
  • Output: Return to the DataTable object after successful reading, and return to null if read failed reading.
  • Design idea: using XmlDocumentSelectNodesThe method selects the node collection that specifies the XPath expression, traverses the node collection, and creates a DataTable column based on the node's child nodes. Then iterate through each node, taking the child node's name and text content as the row data of the DataTable. Finally, the DataTable object is returned.

UpdateXmlFromDataTable(XmlDocument xmlDoc, DataTable dataTable, string elementName): void

  • Function: Update data in DataTable object to XML file.
  • Enter: XmlDocument object, DataTable object, name of the node element to be updated.
  • Output: None.
  • Design idea: First, clear all child nodes under the root node of XmlDocument. Then iterate through each row of the DataTable, create a new XmlElement, and set the child nodes of the XmlElement based on the column name and row data of the DataTable. Finally add the new XmlElement to the root node of the XmlDocument.

GetNodeValue(XmlDocument xmlDoc, string xpath): string

  • Function: Get the value of the specified node according to the XPath expression.
  • Input: XmlDocument object, XPath expression.
  • Output: The value of the node, if the node does not exist, return null.
  • Design idea: using XmlDocumentSelectSingleNodeThe method selects the specified node according to the XPath expression, and then returns the node's InnerText.

SetNodeValue(XmlDocument xmlDoc, string xpath, string value): void

  • Function: Set the value of the specified node according to the XPath expression.
  • Input: XmlDocument object, XPath expression, the value to be set.
  • Output: None.
  • Design idea: using XmlDocumentSelectSingleNodeThe method selects the specified node according to the XPath expression, and then sets the node's InnerText to the specified value.

GetAttributeValue(XmlDocument xmlDoc, string xpath, string attributeName): string

  • Function: Get the attribute value of the specified node based on the XPath expression and attribute name.
  • Input: XmlDocument object, XPath expression, property name.
  • Output: The value of the property, if the property does not exist, return null.
  • Design idea: using XmlDocumentSelectSingleNodeThe method selects the specified node according to the XPath expression, and then obtains the value of the attribute according to the attribute name.

SetAttributeValue(XmlDocument xmlDoc, string xpath, string attributeName, string value): void

  • Function: Set the attribute value of the specified node according to the XPath expression and attribute name.
  • Enter: XmlDocument object, XPath expression, property name, value to set.
  • Output: None.
  • Design idea: using XmlDocumentSelectSingleNodeThe method selects the specified node according to the XPath expression, and then sets the value of the attribute according to the attribute name.

UpdateNodeValueInFile(string filePath, string xpath, string value): void

  • Function: Update node values ​​in XML files based on file path, XPath expression, and value.
  • Enter: file path, XPath expression, value to be set.
  • Output: None.
  • Design idea: First load the XML document from the file path, then call the SetNodeValue function to set the value of the specified node, and finally save the XML document to the file.

UpdateAttributeValueInFile(string filePath, string xpath, string attributeName, string value): void

  • Function: Update attribute values ​​in XML files based on file path, XPath expression, attribute name, and value.
  • Enter: file path, XPath expression, attribute name, value to set.
  • Output: None.
  • Design idea: First load the XML document from the file path, then call the SetAttributeValue function to set the attribute value of the specified node, and finally save the XML document to the file.

This is the article about writing a simple class library XMLHelper based on C# to operate XML. For more related C# operation XML content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!