SoFunction
Updated on 2025-04-11

Four common ways to read XML files in C#

XML

Introduction

Xml is a cross-platform, content-dependent technology in the Internet environment, and is a powerful tool for processing structured document information. XML is a simple data storage language that uses a series of simple tags to describe data, which can be established in a convenient way. Although XML takes up more space than binary data, XML is extremely simple and easy to master and use.

Format

Example:

file name:

<?xml version="1.0" encoding="UTF-8"?>
<notes>
    <note Type="1">
      <to>Tove</to>
      <from>Jani</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
    </note>
    <note Type="2">
      <to>Tove</to>
      <from>Jani</from>
      <heading>Reminder</heading>
      <body>Don't forget me this weekend!</body>
    </note>
</notes>

c# method to read XML file

Using XmlDocument

Using XmlDocument is a way to read XML files based on the document structure model. In XML files, we can regard XML as a tree composed of document declarations (Declare), elements (Element), attributes (Attribute), text (Text), etc. The initial node is called the root node, and each node can have its own child node. After obtaining a node, you can obtain the value of this node or some other attributes through a series of attributes or methods. For example:

  • xn represents a node
  • ;//The name of this node
  • ;//The value of this node
  • ;//All child nodes of this node
  • ;//The parent node of this node
  •  .......

operate

//Declare the XmlDocument object and load the XML fileXmlDocument doc = new XmlDocument();
(@""); //This is the path to the XML file
#region Get node//Get the root node nodeXmlNode xn = ("notes");
//Get all children of the root nodeXmlNodeList xnl = ;

foreach (XmlNode xNode in xnl)
{
    //Convert nodes to elements to get the attribute value of nodes    XmlElement xe = (XmlElement)xNode;
    //Get the attribute value of the note node    string noteType = ("Type").ToString();
    //Get all children of the note node    XmlNodeList xnl0 = ;
    string body = (3).InnerText;
    //Modify the node value    (0).InnerText = "Tovv";
}
#endregion

#region Add nodes -- The following is an additional//Create a node and set the node's propertiesXmlElement xelKey = doc.createElement_x("note");
XmlAttribute xelType = ("Type");
 = "3";
(xelType);
//Create child nodesXmlElement xelAuthor = doc.createElement_x("to");
 = "Tang";
(xelAuthor);
//note, and save the entire file(xelKey);
(@"..\..\");
#endregion
    
#region Add nodes -- The following is the coverageXmlDocument doc = new XmlDocument();
("&lt;notes&gt;&lt;/notes&gt;");//Use this sentence, all the previous data will be overwritten, only the data you added#endregion

#region Delete nodesXmlElement xe = ; 
string strPath = ("/notes/notes[@Type=\"{0}\"]", [1].());
XmlElement selectXe = (XmlElement)(strPath); //selectSingleNode obtains the first node that meets the criteria according to the XPath expression.(selectXe); //Remove node#endregion

Notice

When annotations are contained in the XML file, an error will occur because annotations are also a node type. Without special explanation, it will default to it as a node (Node). Therefore, an error will be reported when converting a node into an element. "The object of type " cannot be cast to type ""."

Solution:

XmlDocument xmlDoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
 = true;//Ignore the comments in the documentXmlReader reader = (@"..\..\", settings);
(reader);

//After the final reading is finished, remember to turn off the reader();

Using XmlTextReader/XmlTextWriter

When reading data using XmlTextReader, first create a stream, and then use the read() method to continuously read downward, performing corresponding operations based on the type of read node.

operate

//Use XmlTextReader to read the fileXmlTextReader reader = new XmlTextREADER(@"");

while(())
{
    if( == )
    {
        //Read node attribute        if( == "note")
        {
            //The first method            string nodeType = (0);
            
            //Another way            for(int i = 0; i &lt; ; i++)
            {
                (i);
                string str = "property:" +  + "=" + ;
            }
        }
        //Read the value of the node        if( == "to")
        {
        	string nodeTo = ().Trim();    
        }
        if( == "from")
        {
            string nodeFrom = ().Trim();
        }
        //When the node type is the tail node        if( == )
        {
            
        }
    }
}

(); //Close the read file stream

//Write files using XmlTextWriter// When writing a file, the default is to overwrite the previous file. If the file name does not exist, it will create this file.XmlTextWriter myXmlTextWriter = new XmlTextWriter(@"", null);
//Use the Formatting property to specify the format you want to set XML to.  This way, the child elements can be indented by using the Indentation and IndentChar properties. = ;

(false);
("notes"); //Write to the starting node of notes
("note information"); //Write comment("note"); //Write to the start node of the note
("Type", "3"); //Write attributes to note node
("to","hong"); //Write to note child node
(); //The tail node of the write note(); //Write to the tail node of notes
(); //End write(); //Close the write stream

Using Linq to Xml

Linq is a new feature that appeared in C# 3.0. Using it can easily operate many data sources, including XML files. Using Linq is very convenient and relatively simple to operate XML files.

operate

XElement xe = (@"");

#region Read dataIEnumerable&lt;XElement&gt; elements = from ele in ("note") select ele;

foreach(var ele in elements)
{
    //Get the node's properties	string nodeType = ("Type").Value;
    //Get the child node value of the node    string nodeTo = ("to").Value;
}
#endregion

#region Insert dataXElement record = new XElement(
	new XElement("note",
                 new XAttribute("Type", "3"),
                 new XElement("to", "tang"),
                 new XElmeent("from", "hong")
                )
);
(record);
(@"");
#endregion
    
#region Delete data//Delete selected dataIEnumerable&lt;XElement&gt; elements = from ele in ("note")
    where (string)("Type") == 1
    select ele;

if(() &gt; 0)
    ().Remove();

(@"");

//Delete all dataIEnumerable&lt;XElement&gt; elements = from ele in ("note") select ele;

if(() &gt; 0)
    ();

(@"");
#endregion

#region Modify dataIEnumerable&lt;XElement&gt; elements = from ele in ("note")
    where (string)("Type") == 1
    select ele;

if(() &gt; 0)
{
    XElement first = ();
    //Set new properties    ("Type", 5);
    //Replace new node    (
        new XElement("to", "tangtang"),
        new XElmeent("from", "hong")
    );
}
(@"");
#endregion

Using DataSet

Provides strong support for XML, and its main thing is to interact with XML through datasets.

operate

DataSet ds = new DataSet();
//Read the file(@"");

//Display datastring nodeTo = [0].Rows[0]["to"];
//Modify the data[0].Rows[0]["to"] = "tos";
//Insert dataDataRow dr = [0].NewRow();
dr["to"] = "dsds";
dr["from"] = "wang";
[0].(dr);
//Delete dataDataRow delR = [0].Rows[0];
[0].(delR);

//Save data(@"");

This is the end of this article about four common methods of reading XML files in C#. For more related C# reading XML content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!