SoFunction
Updated on 2025-03-07

C# XML basics summary (retrieve the content of XML files)

Preface:

Recently, a third-party project was connected to the data transmission format of the project is XML. Since I only came into contact with a small amount of data formats that are XML interfaces when I was in the medical industry for many years, I have almost never been exposed to it since then. Therefore, I still feel that there are many blind spots and shortcomings in XML, so I summarized the XML-related knowledge points through some online information.

What is XML?

  • XML is an extensible markup language.
  • XML is a markup language that looks a lot like HTML.
  • XML is designed to transmit data, not display data.
  • XML tags are not predefined. You need to define the tags yourself.
  • XML is designed to be self-descriptive.
  • XML is the recommended standard for W3C.

Pros and cons of XML

Advantages of XML

  • The grammar is rigorous, the format is unified, and it meets the standards.
  • Easy to interact remotely with other systems, and data sharing is more convenient.

Disadvantages of XML

  • The scalability, flexibility and readability are poor.
  • XML files are huge, the file format is complex, and the transmission accounts for bandwidth.
  • The server-side and client-side parsing XML takes a lot of resources and time.

Simple XML example

Online xml verification tool:http://tools./code/xmlcodeformat

<?xml version="1.0" encoding="utf-8"?>
<books>
    <book>
        <author>Time Chaser</author>
        <title>XMLStudy tutorial</title>
        <publisher>Time Publishing House</publisher>
    </book>
</books>

5 predefined entity references in XML

Escape characters symbol name
& & And number
&lt; < Less than
&gt; > Greater than
&apos; ' Ellipsis
&quot; " quotation marks

Strictly speaking, it is illegal to have only characters "<" and "&" in XML. Ellipsis, quotes, and greater than are legal. At this time, Xml has two solutions to deal with this problem.

CDATA

Escape characters

C# converts special symbols into escape characters

/// &lt;summary&gt;
        /// Convert special symbols to escape characters        /// &lt;/summary&gt;
        /// &lt;param name="xmlStr"&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public string XmlSpecialSymbolConvert(string xmlStr)
        {
            return ("&amp;", "&amp;amp;").Replace("&lt;", "&amp;lt;").Replace("&gt;", "&amp;gt;").Replace("\'", "&amp;apos;").Replace("\"", "&amp;quot;");
        }

C# Create a simple XML file

/// &lt;summary&gt;
        /// Create Xml file        /// &lt;/summary&gt;
        public void CreateXmlFile()
        {
            XmlDocument xmlDoc = new XmlDocument();
            //Create a type declaration node            XmlNode node = ("1.0", "utf-8", "");
            (node);
            //Create Xml root node            XmlNode root = ("books");
            (root);

            XmlNode root1 = ("book");
            (root1);

            //Create child nodes            CreateNode(xmlDoc, root1, "author", "Time Chaser");
            CreateNode(xmlDoc, root1, "title", "XML Learning Tutorial");
            CreateNode(xmlDoc, root1, "publisher", "Time Publishing House");
            //Save the file to the specified location            ("D://");
        }

        /// &lt;summary&gt;    
        /// Create node        /// &lt;/summary&gt;    
        /// <param name="xmlDoc">xml document</param>        /// <param name="parentNode">Xml parent node</param>        /// <param name="name">Node name</param>        /// <param name="value">node value</param>        ///   
        public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            //Create the corresponding Xml node element            XmlNode node = (, name, null);
             = value;
            (node);
        }

Create the generated Xml file

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;books&gt;
  &lt;book&gt;
    &lt;author&gt;Time Chaser&lt;/author&gt;
    &lt;title&gt;XMLStudy tutorial&lt;/title&gt;
    &lt;publisher&gt;Time Publishing House&lt;/publisher&gt;
  &lt;/book&gt;
&lt;/books&gt;

C# Add nodes in XML file

This time we did operations in the last newly created XML file, adding a new node named publishdate under the book secondary node, and the value of this node is 2022-03-26.

private static void AppendNode()
        {
            XmlDocument xmlDoc = new XmlDocument();
            ("D://");//Load the Xml file            XmlNode root = ("books/book");//Select the book node to add child nodes            //Create a new Xml node element            XmlNode node = (, "publishdate", null);
             = "2022-03-26";
            (node);//Add the created item child node to the tail of the item node            ("D://");//Save the modified Xml file content        }

XML file content after successful addition of node

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;books&gt;
  &lt;book&gt;
    &lt;author&gt;Time Chaser&lt;/author&gt;
    &lt;title&gt;XMLStudy tutorial&lt;/title&gt;
    &lt;publisher&gt;Time Publishing House&lt;/publisher&gt;
    &lt;publishdate&gt;2022-03-26&lt;/publishdate&gt;
  &lt;/book&gt;
&lt;/books&gt;

C# Modify the data of XML file nodes

This time we operated in the first newly created XML file, and changed the content of author under the second-level node of the book to: Da Yao classmate

private static void UpdateXml()
        {
            XmlDocument xmlDoc = new XmlDocument();
            ("D://");//Load the Xml file            XmlNode xns = ("books/book");//Find the node to be modified            XmlNodeList xmlNodeList = ;//Retrieve all child nodes under the book node
            foreach (XmlNode xmlNode in xmlNodeList)
            {
                XmlElement xmlElement = (XmlElement)xmlNode;//Convert the node to type                if (=="author")//Distinguish whether the child node is the node to be searched                {
                     = "Yao Classmate";//Set new value                    break;
                }
            }
            ("D://");//Save the modified Xml file content        }

Modified XML file content

&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;books&gt;
  &lt;book&gt;
    &lt;author&gt;Classmate Da Yao&lt;/author&gt;
    &lt;title&gt;XMLStudy tutorial&lt;/title&gt;
    &lt;publisher&gt;Time Publishing House&lt;/publisher&gt;
  &lt;/book&gt;
&lt;/books&gt;

C# deletes the specified node in the XML file

This time we operated in the first newly created XML file and deleted the author node.

private static void DeleteXmlNode()
        {
            XmlDocument xmlDoc = new XmlDocument();
            ("D://");//Load the Xml file            XmlNode xns = ("books/book");//Find the root node to be deleted
            #region Delete author node
            var delNode = ("books/book/" + "author");
            (delNode);

            #endregion

            ("D://");//Save the Xml file content after the operation        }

C# clears the specified XML node data

This time we operated in the first newly created XML file to clear the data under the author node.

private static void ClearDataXmlNode()
        {
            XmlDocument xmlDoc = new XmlDocument();
            ("D://");//Load the Xml file            XmlNode xns = ("books/book");//Find the root node to be deleted
            #region Clear data under author node            XmlNodeList xmlNodeList = ;//Retrieve all child nodes under the book node            foreach (XmlNode xmlNode in xmlNodeList)
            {
                XmlElement xmlElement = (XmlElement)xmlNode;//Convert the node to type                if ( == "author")//Distinguish whether the child node is the node to be searched                {
                    //Clear the data under the author node                    ();//Delete all contents of this node                }
            }
            #endregion

            ("D://");//Save the Xml file content after the operation        }

Learning reference materials

w3cSchool-XML Tutorial

Summary of common classes and attributes used to control XML serialization in .NET

This is the article about the introduction to the basic introduction of C# XML (add, delete, modify and clarify the content of XML files). For more related basic introduction of C# XML, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!