SoFunction
Updated on 2025-03-07

Detailed explanation of the example code for reading XML in c#

XML files are a commonly used file format, such as files in WinForm and Web programs, and many important places have it. 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. Microsoft also provides a series of class libraries to help us store XML files in our applications.

"There are generally two models for accessing and then operating XML files in programs, namely using DOM (Document Object Model) and streaming models. The advantage of using DOM is that it allows editing and updating XML documents, random access to data in the document, and can use XPath query. However, the disadvantage of DOM is that it requires loading the entire document into memory at one time. For large documents, this will cause resource problems. The streaming model solves this problem well because it uses the concept of streaming to access XML files, that is, there is only the current node in memory at any time, but it also has its shortcomings. It is read-only, forward-only, and cannot perform backward-navigation operations in the document."

Below I will introduce three commonly used methods to read XML files. They are

1: Using XmlDocument

2: Using XmlTextReader

3: Using Linq to Xml

Here I will first create an XML file, and all the methods named below are based on this XML file, and the file content is as follows:

 <?xml version="1.0" encoding="utf-8"?>
   <bookstore>
    <!--Recording the information of the book-->
    <book Type="Compulsory Courses" ISBN="7-111-19149-2">
     <title>Data structure</title>
     <author>Yan Weimin</author>
     <price>30.00</price>
    </book>
    <book Type="Compulsory Courses" ISBN="7-111-19149-3">
    <title>Router and switched Internet basics</title>
    <author>Cheng Qingmei</author>
    <price>27.00</price>
   </book>
   <book Type="Compulsory Courses" ISBN="7-111-19149-4">
    <title>Computer hardware technology foundation</title>
    <author>Li Jican</author>
    <price>25.00</price>
   </book>
   <book Type="Compulsory Courses" ISBN="7-111-19149-5">
    <title>Software quality assurance and management</title>
    <author>Zhu Shaomin</author>
    <price>39.00</price>
   </book>
   <book Type="Compulsory Courses" ISBN="7-111-19149-6">
    <title>Algorithm design and analysis</title>
    <author>Wang Hongmei</author>
    <price>23.00</price>
   </book>
   <book Type="Electronics" ISBN="7-111-19149-1">
    <title>Computer operating system</title>
    <author>7-111-19149-1</author>
    <price>28</price>
   </book>
  </bookstore>

For the convenience of reading, I also define a book entity class called BookModel, the specific content is as follows:

 using System;
   using ;
   using ;
   using ;
   
   namespace useXmlDocument
   {
     public class BookModel
     {
      public BookModel()
      { }
      /// <summary>
      /// The corresponding course type      /// </summary>
      private string bookType;
   
      public string BookType
      {
        get { return bookType; }
        set { bookType = value; }
      }
   
      /// <summary>
      /// The ISBN number corresponding to the book      /// </summary>
      private string bookISBN;
   
      public string BookISBN
      {
        get { return bookISBN; }
        set { bookISBN = value; }
      }
   
      /// <summary>
      /// Title of the book      /// </summary>
      private string bookName;
   
      public string BookName
      {
        get { return bookName; }
        set { bookName = value; }
      }
   
      /// <summary>
      /// author      /// </summary>
      private string bookAuthor;
   
      public string BookAuthor
      {
        get { return bookAuthor; }
        set { bookAuthor = value; }
      }
   
      /// <summary>
      /// price      /// </summary>
      private double bookPrice;
   
      public double BookPrice
      {
        get { return bookPrice; }
        set { bookPrice = value; }
      }
    }
  }

1. Use 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 Represent a node
   ;//The name of this node   ;//The value of this node   ;//All child nodes of this node   ;//The parent node of this node   .......

1.1 Read all data.

When using it, first declare an XmlDocument object, then call the Load method to load the XML file from the specified path.

XmlDocument doc = new XmlDocument();
(@"..\..\");

Then you can get the specified node by calling SelectSingleNode and get the specific attribute value through GetAttribute. See the following code

  // Get the root node bookstore   XmlNode xn = ("bookstore");
   
   
   // Get all the children of the root node   XmlNodeList xnl = ;
   
   foreach (XmlNode xn1 in xnl)
   {
    BookModel bookModel = new BookModel();
    // Convert nodes to elements to get the attribute value of nodes    XmlElement xe = (XmlElement)xn1;
    // Get the attribute values ​​of the two attributes Type and ISBN     = ("ISBN").ToString();
     = ("Type").ToString();
    // Get all children of the Book node    XmlNodeList xnl0 = ;
    =(0).InnerText;
    =(1).InnerText;
    =((2).InnerText);
    (bookModel);
  }
   = bookModeList;

Under normal circumstances, the above code seems to have no problem, but when reading the above XML file, an error occurs. The reason is that there are comments in the above XML file. You can refer to the third line in the file, and I added a comment casually. The comment is 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 "".

Fortunately, it comes with a solution, that is, when reading, tell the compiler to let it ignore the comment information. Modifications are as follows:

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.

 ();

This way it will not cause errors.

The final running results are as follows:

1.2 Add information to a book.

When adding new data to the file, first load the entire document through XmlDocument, then obtain the root node by calling the SelectSingleNode method, create elements through the CreateElement method, create attributes with CreateAttribute, mount the current node on other nodes with AppendChild, and set the attributes of the node using SetAttributeNode. The specific code is as follows:

Load the file and select the desired node:

XmlDocument doc = new XmlDocument();
(@"..\..\");
XmlNode root = ("bookstore");

Create a node and set the node's properties:

  XmlElement xelKey = ("book");
   XmlAttribute xelType = ("Type");
    = "adfdsf";
   (xelType);

Create child nodes:

  XmlElement xelAuthor = ("author");
    = "dfdsa";
   (xelAuthor);

Finally, mount the book node on the desired node and save the entire file:

(xelKey);
(@"..\..\");

Using the above method, add data to the existing file. If you want to overwrite all the original data, you can change it and use the LoadXml method:

  XmlDocument doc = new XmlDocument();
   ("<bookstore></bookstore>");//Use this sentence,Will overwrite all previous data,Only the data you have added

You can directly select the root node. You don’t use the SelectSingleNode method to select the root node, and just create the node. The code is the same as above.

1.3 Delete a certain data

If you want to delete a certain node, you can directly find its parent node and then call the RemoveChild method. The key question now is how to find this node. The SelectSingleNode above can pass an Xpath table. We use the ISBN number of the book to find the node where the book is located. As follows:

 XmlElement xe = ; // DocumentElement Gets the root XmlElement of the xml document object.   string strPath = ("/bookstore/book[@ISBN=\"{0}\"]", [1].());
   XmlElement selectXe = (XmlElement)(strPath); //selectSingleNode obtains the first node that meets the criteria according to the XPath expression.   (selectXe);

"/bookstore/book[@ISBN=\"{0}\"]" is an Xpath expression. Find the book with the ISBN number as the selected row. For knowledge about Xpath, please refer to: XPath Syntax

1.4 Modify a certain piece of data

To modify a piece of data, first use the Xpath expression to find the node that needs to be modified. Then, if it is an element, directly assign values ​​to the element. If it is an attribute, use the SetAttribute method to set it. As follows:

  XmlElement xe = ; // DocumentElement Gets the root XmlElement of the xml document object.   string strPath = ("/bookstore/book[@ISBN=\"{0}\"]", [1].());
   XmlElement selectXe = (XmlElement)(strPath); //selectSingleNode obtains the first node that meets the criteria according to the XPath expression.   ("Type", [0].());// You can also add an attribute through SetAttribute   ("title").Item(0).InnerText = [2].();
   ("author").Item(0).InnerText = [3].();
   ("price").Item(0).InnerText = [4].();
   (@"..\..\");

2. Use XmlTextReader and XmlTextWriter

XmlTextReader and XmlTextWriter read and write XML files in the form of streams.

2.1XmlTextReader

When reading data using XmlTextReader, first create a stream, and then use the read() method to continuously read downwards, performing corresponding operations according to the type of read nodes. As follows:

   

 XmlTextReader reader = new XmlTextReader(@"..\..\");
        List<BookModel> modelList = new List<BookModel>();
        BookModel model = new BookModel();
        while (())
        {
          
          if ( == )
          {
            if ( == "book")
            {
               = (0);
               = (1);
            }
            if ( == "title")
            {
              =().Trim();
            }
            if ( == "author")
            {
               = ().Trim();
            }
            if ( == "price")
            {
               = (().Trim());
            }
          }
   
          if ( == )
          {
            (model);
            model = new BookModel();
          }
   
          
        }
        (-1);
         = modelList;

The key is that when reading attributes, you must first know which node has several attributes, and then read them through the GetAttribute method. Another method can be used to read attributes, which is to use the MoveToAttribute method. See the following code:

  if ( == "book")
     {
       for (int i = 0; i &lt; ; i++)
       {
         (i);
         string str = "property:" +  + "=" + ;
       }
        = (0);
        = (1);
    }

The effects are as follows:

2.2XmlTextWriter

When writing a file, the default is to overwrite the previous file. If this file name does not exist, it will create this file. First, set the XML file format you want to create.

 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.    = ;

Then you can create elements through WriteStartElement and WriteElementString methods. The difference between these two is that if there are elements of child nodes, then use WriteStartElement when creating them, and then create child elements. After creation, you need to call the corresponding WriteEndElement to tell the compiler. After creation, use WriteElementString to create individual elements and use WriteAttributeString to create attributes. As follows:

  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);
        ("bookstore");
   
        ("Record the information of the book");
        ("book");
   
        ("Type", "Electronics");
        ("ISBN", "111111111");
   
        ("author","Zhang San");
        ("title", "Career Planning");
        ("price", "16.00");
   
        ();
        ();
   
        ();
        ();

3. Use 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 to operate XML files is very convenient and relatively simple. Let’s look at the code directly,

First define a method to display the queryed data

  private void showInfoByElements(IEnumerable<XElement> elements)
      {
        List<BookModel> modelList = new List<BookModel>();
        foreach (var ele in elements)
        {
          BookModel model = new BookModel();
           = ("author").Value;
           = ("title").Value;
           = (("price").Value);
          =("ISBN").Value;
          =("Type").Value;
          
          (model);
        }
         = modelList;
      }

3.1 Read all data

Directly find this node where the element is the book, and then traverse and read all the results.

  private void btnReadAll_Click(object sender, EventArgs e)
      {
        XElement xe = (@"..\..\");
        IEnumerable<XElement> elements = from ele in ("book")
                         select ele;
        showInfoByElements(elements);
      }

3.2 Insert a data

The insertion nodes and attributes are both new, as follows:

  private void btnInsert_Click(object sender, EventArgs e)
       {
         XElement xe = (@"..\..\");
         XElement record = new XElement(
         new XElement("book",
         new XAttribute("Type", "Electronics"),
         new XAttribute("ISBN","7-111-19149-1"),
         new XElement("title", "Computer operating system"),
         new XElement("author", "7-111-19149-1"),
        new XElement("price", 28.00)));
        (record);
        (@"..\..\");
        ("Insert successfully!");
        btnReadAll_Click(sender, e);
      }

3.3 Delete selected data

First, get the selected line, find this element through the ISBN number, and then use the Remove method to delete it directly, as follows:

  private void btnDelete_Click(object sender, EventArgs e)
      {
        if ( != null)
        {
          //[1] Corresponding to ISBN number          string id = [1].();
          XElement xe = (@"..\..\");
          IEnumerable&lt;XElement&gt; elements = from ele in ("book")
                           where (string)("ISBN") == id
                          select ele;
         {
          if (() &gt; 0)
            ().Remove();
          }
          (@"..\..\");
          ("Delete successfully!");
          btnReadAll_Click(sender, e);
   
        }
      }

3.4 Delete all data

Similar to the above, select all the data and use the Remove method as follows:

  private void btnDeleteAll_Click(object sender, EventArgs e)
      {
        XElement xe = (@"..\..\");
        IEnumerable&lt;XElement&gt; elements = from ele in ("book")
                         select ele;
        if (() &gt; 0)
        {
          ();
        }
        (@"..\..\");
        ("Delete successfully!");
        btnReadAll_Click(sender, e);
      }

3.5 Modify a record

First, get a certain node to be modified, then use SetAttributeValue to modify the attribute, and use ReplaceNodes to modify the node element. as follows:

  private void btnSave_Click(object sender, EventArgs e)
   {
     XElement xe = (@"..\..\");
     if ( != null)
     {
       //[1] Corresponding to ISBN number       string id = [1].();
       IEnumerable&lt;XElement&gt; element = from ele in ("book")
                       where ("ISBN").Value == id
                      select ele;
      if (() &gt; 0)
      {
        XElement first = ();
        ///Set new properties        ("Type", [0].());
        ///Replace new node        (
             new XElement("title", [2].()), 
             new XElement("author", [3].()),
             new XElement("price", (double)[4].Value) 
             );
      }
      (@"..\..\");
   
      ("The modification was successful!");
      btnReadAll_Click(sender, e);
    }
  }

The final effect is as follows:

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.