SoFunction
Updated on 2025-03-03

Detailed explanation and examples of C#'s operations using XML files

Preface

XML is the short name of Extensible Markup Language, an extensible markup language used to store and transfer data. It is used in data exchange, data storage, web services, network protocols and other scenarios.

XML has several characteristics such as scalability, structure, standardization, and simple and easy to read.

Basic structure

The basic XML structure includes document declarations, root elements, child elements, attributes, comments, processing instructions, etc.

<?xml version="1.0" encoding="UTF-8"?>
<Root element>
  <Sub-elements property="Attribute Value">content</Sub-elements>
  <!-- 注释content -->
  <?Processing instructions ?>
</Root element>

Documentation Statement

Document declarations are mainly used to describe XML documentsVersionandEncoding format, each document must contain a declaration and start with the document. The following statement is: Version 1.0's encoding format is UTF-8.

<?xml version="1.0" encoding="UTF-8"?>

Root element

The root element surrounds all data in the document and is the root of other elements. Each document must have a root element. The following example: There is a configure root element with other content under it.

<configure>
  <Description>Fountain WinForm App</Description>
  <Files>
    <File Version="1.2.11.0" Name="" DateTime="2023-4-26" />
  </Files>
</configure>

Sub-elements

A child element is the basic unit of a document, which contains elements such as attributes, content, etc. The following example:

<name>Apple</name>
 
<File Version="1.2.11.0" Name="" DateTime="2023-4-26" />

property

Elements can have attributes for additional information about elements. It is defined in the Start tag and appears in the form of name/key value pairs. The following example: The File element has Version, Name, and DateTime attributes.

<File Version="1.2.11.0" Name="" DateTime="2023-4-26" />

Comments

Comments Add comments or descriptions to the document, starting with <!-- and ending with -->. The following example:

&lt;configure&gt;
  &lt;Description&gt;Fountain WinForm App&lt;/Description&gt;
  &lt;Files&gt;
    &lt;!-- The file name of the program、Version、Update date --&gt;
    &lt;File Version="1.2.11.0" Name="" DateTime="2023-4-26" /&gt;
  &lt;/Files&gt;
&lt;/configure&gt;

Processing instructions

Processing instructions provide instructions on how the XML processor processes documents. Example below: Identify the style sheet of the document.

 <?xml-stylesheet type="text/xsl" href="" rel="external nofollow" ?>

Namespace

Mechanism used to define the scope and scope of elements and attributes in a document.

Document operation

Common operations can be completed through classes in the namespace. The following table is the classes related to operating XML documents.

kind describe
XmlDocument Create, modify and save XML documents.
XmlNode Represents a single node in an XML document
XmlElement Access the name, attribute, and child elements of an element.
XmlTextWriter Provides fast, non-cache writers.
XPathDocument Provides read-only form to read XML documents.
XPathNavigator Provide browsing and extracting XML node data
XmlAttribute Access the name and value of XML attributes
XmlText Access text content

Create a document

Declare the XML document through CreateXmlDeclaration of XmlDocument, then create an XML element through CreateElement, and finally save the XML file. The following is a code to learn more about the creation of XML documents.

using System;
using ;
using ;
using ;
 
namespace 
{
    public partial class XMLDemoForm : Form
    {
        public XMLDemoForm()
        {
            InitializeComponent();
        }
        /// &lt;summary&gt;
        /// Create a document        /// &lt;/summary&gt;
        /// &lt;param name="sender"&gt;&lt;/param&gt;
        /// &lt;param name="e"&gt;&lt;/param&gt;
        private void ButtonCreate_Click(object sender, EventArgs e)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                // XML declaration                XmlDeclaration xmlDeclaration = ("1.0", "utf-8", "yes");
                (xmlDeclaration);
                //Create root element                XmlElement rootNode = ("configure");
                (rootNode);
                // Create Description child element                XmlElement descSubElement = ("Description");
                //Element content                 = "Fountain WinForm App";
                (descSubElement);
 
                // Create Updater child elements                XmlElement updaterSubElement = ("Updater");
                (updaterSubElement);
 
                // Create url child elements                XmlElement urlSubElement = ("url");
                //Intermediate text                 = "http://127.0.0.1/update";
                // Add to parent node                (urlSubElement);
 
                XmlElement versionSubElement = ("Version");
                //Intermediate text                 = "3.8.0.24043";
                // Add to parent node                (versionSubElement);
 
                // Create Files child elements                XmlElement filesSubElement = ("Files");
                (filesSubElement);
                // Create File child elements                XmlElement fileSubElement = ("File");
                // Attributes                ("Version", "1.2.11.0");
                ("Name", "");
                ("DateTime", ("yyyy-MM-dd"));
                (fileSubElement);
                // Save the document                (("{0}{1}{2}", ,, ""));
            }
            catch (Exception ex)
            {
                ();
            }
        }
    }
}

Running results:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<configure>
  <Description>Fountain WinForm App</Description>
  <Updater>
    <url>http://127.0.0.1/update</url>
    <Version>3.8.0.24043</Version>
  </Updater>
  <Files>
    <File Version="1.2.11.0" Name="" DateTime="2024-04-13" />
  </Files>
</configure>

Read the document

Load the XML file on the XML document through the Load of XmlDocument, then obtain the specified node element through SelectSingleNode, and then obtain the specific attribute value through GetAttribute. The following is a code to learn more about reading XML documents.

using System;
using ;
using ;
using ;
using ;
 
namespace 
{
    public partial class XMLDemoForm : Form
    {
        public XMLDemoForm()
        {
            InitializeComponent();
        }
        /// &lt;summary&gt;
        /// Read the document        /// &lt;/summary&gt;
        /// &lt;param name="sender"&gt;&lt;/param&gt;
        /// &lt;param name="e"&gt;&lt;/param&gt;
        private void ButtonRead_Click(object sender, EventArgs e)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                (("{0}{1}{2}", , , ""));
                // Get Files                XmlNode XmlNode = ("configure");
                // Get all the children of the root node                XmlNodeList xmlNodeList = ;
                StringBuilder stringBuilder = new StringBuilder();
                // Loop reading                foreach (XmlNode xmlNode in xmlNodeList)
                {
                    // Determine whether the node has children                    if (&gt;0)
                    {
                        foreach (XmlNode subXmlNode in )
                        {
                            (("{0}:{1}", , ));
                            // Read element attributes                            if (!=null &amp;&amp; &gt;0)
                            {
                                for (int i = 0; i &lt; ;i++)
                                {
                                    (("{0}:{1} property{2}={3}",
                                        , 
                                        ,
                                        [i].Name,
                                        [i].Value));
                                }
                            }
                        }
                        continue;
                    }
                    (("{0}:{1}", ,));
                }
                // (());
                (());
            }
            catch (Exception ex)
            {
                ();
            }
        }
    }
}

Running results:

#text:Fountain WinForm App
url:http://127.0.0.1/update
Version:3.8.0.24043
File:
File: Property Version=1.2.11.0
File: Attribute Name=
File: Attribute DateTime=2024-04-13

Modify the document

Load the XML file into the XML document through the Load of XmlDocument, then read to the element node, delete the element node, change the attribute value, element text, etc., and finally save the XML file. The following is a code to learn more about the modification of XML documents.

using System;
using ;
using ;
using ;
using ;
 
namespace 
{
    public partial class XMLDemoForm : Form
    {
        public XMLDemoForm()
        {
            InitializeComponent();
        }
        /// &lt;summary&gt;
        /// Modify the document        /// &lt;/summary&gt;
        /// &lt;param name="sender"&gt;&lt;/param&gt;
        /// &lt;param name="e"&gt;&lt;/param&gt;
        private void ButtonModify_Click(object sender, EventArgs e)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                (("{0}{1}{2}", , , ""));
                // Get the root element                XmlNode rootNode = ;
                // Get the main information                XmlNodeList xmlNodeList = ("Updater");
                foreach (XmlNode xmlNodeUpdate in xmlNodeList)
                {
                    XmlNodeList xmlNodeMainInfo = ;
                    foreach (XmlNode xmlMainInfo in xmlNodeMainInfo)
                    {
                        if ("url".Equals(,))
                        {
                            // Delete the url element node                            (xmlMainInfo);
                            break;
                        }
                    }
                }
                // Loop reading                foreach (XmlNode xmlNode in xmlNodeList)
                {
                    if ( &gt; 0)
                    {
                        foreach (XmlNode subXmlNode in )
                        {
                            if ( != null &amp;&amp;  &gt; 0)
                            {
                                for (int i = 0; i &lt; ; i++)
                                {
                                    if ("DateTime".Equals([i].Name,))
                                    {
                                        // Modify element node attributes                                        [i].Value = ("yyyy-MM-dd");
                                    }
                                }
                            }
                        }
                        continue;
                    }
                }
                (("{0}{1}{2}", , , ""));
            }
            catch (Exception ex)
            {
                ();
            }
        }
    }
}

Running results:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<configure>
  <Description>Fountain WinForm App</Description>
  <Updater>
    <Version>3.8.0.24043</Version>
  </Updater>
  <Files>
    <File Version="1.2.11.0" Name="" DateTime="2024-04-13" />
  </Files>
</configure>

summary

The above XML document related content and how to implement the creation, modification and reading of files in C#. I hope it can help you to provide some reference for XML applications. There are other ways to create, modify and read XML. It will be introduced later.

This is the article about the detailed explanation and examples of C#’s operations using XML files. For more related contents of C#’s XML files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!