SoFunction
Updated on 2025-03-08

Detailed introduction to reading and writing xml files in C#

The XmlTextWriter class allows you to write XML into a file. This class contains many methods and properties, and using these properties and methods can make it easier for you to process XML. To use this class, you must first create a new XmlTextWriter object, and then you can add XML fragments to this object. This class contains many methods for adding various types of XML elements to XML files. The following table gives the names and descriptions of these methods:

method
describe

WriteStartDocument
XML statement with written version "1.0"

WriteEndDocument
Close any open element or attribute

Close
Close the flow

WriteDocType
Write a DOCTYPE declaration with a specified name and optional attributes

WriteStartElement
Write out the specified start mark

WriteEndElement
Close an element

WriteFullEndElement
Close an element and always write the full end mark

WriteElementString
Write out elements containing string values

WriteStartAttribute
The starting content of writing attributes

WriteEndAttribute
Close the previous WriteStartAttribute call

WriteRaw
Manually write original marks

WriteString
Writing a string

WriteAttributeString
Extract attributes with specified values

WriteCData
Write out the <![CDATA[...]]> block containing the specified text

WriteComment
Write a comment containing the specified text <!--...-->

WriteWhiteSpace
Write out the given blank

WriteProcessingInstruction
Write out processing instructions with spaces between the name and text, as shown below: <?name text?>

If you are very familiar with XML, then you will definitely understand the above methods well. Below we will give an example, in which we will create a document, add some elements, and then close the document. After adding elements, you can also add child elements, attributes and other content. The following code is an example of this, which creates an XML file with the file name title.


Copy the codeThe code is as follows:

using System;
using ;
using ;
public class Sample
{
  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter("", null);
//Write the root element
     ("items");
//Add child elements
     ("title", "Unreal Tournament 2003");
     ("title", "C&C: Renegade");
     ("title", "Dr. Seuss's ABC");
//Close the root element and write the end tag
     ();
//Write XML to the file and close XmlTextWriter
     (); 
  }
}

If you compile and execute the above code, you will create this XML file with the following content:

Copy the codeThe code is as follows:

<items>
    <title>Unreal Tournament 2003</title>
    <title>C&amp;C: Renegade</title>
    <title>Dr. Seuss's ABC</title>
</items>

The above code creates an XmlTextWriter object called writer. When this object is created, it is associated to a file named. Next, the program creates a root property called items, and the WriteStartElement method creates the start tag of this property. Next, the program calls the WriteElementString method to create three child elements. From the above code you can also see that this method uses the first parameter (the title in the above program) as the element's label; and uses the second parameter as the element's value. After you add all the elements, you need to close the root element. At this time, you can call the WriteEndElement method to close the recently opened element; in this example, the recently opened element is the root element. When all the data has been written and the root element has been closed, you can pass the information to your XmlTextWriter. This means that at this time you can call the Close method to close it.

The above code is relatively simple. Let's take a look at an example that uses more methods in the XmlTextWriter class and has more complete functions.

Copy the codeThe code is as follows:

using System;
using ;
using ;
public class Sample
{
  public static void Main()
  {
     XmlTextWriter writer = new XmlTextWriter("", null);
//Use automatic indentation for easy reading
     = ;
//Writing root element
     ("items");
//Start an element
     ("item");
//Add a property to the previously created element
     ("rating", "R");
//Add child elements
     ("title", "The Matrix");
     ("format", "DVD");
//Close the item element
();  // Close element
//Add some spaces between nodes
     ("\n");
//Writing the second element using the original string
     ("<item>" +
                     "<title>BloodWake</title>" +
                     "<format>XBox</format>" +
                     "</item>");
//Writing the third element using a formatted string
     ("\n  <item>\n" +
                     "    <title>Unreal Tournament 2003</title>\n" +
                     "    <format>CD</format>\n" +
                     "  </item>\n");
// Close the root element
     ();
//Write XML to the file and close the writer
     ();
  }
}

After the above code is compiled and run, the file will be obtained, and the content of the file is:

Copy the codeThe code is as follows:

 <items>
  <item rating="R">
    <title>The Matrix</title>
    <format>DVD</format>
  </item>
<item>
    <title>BloodWake</title>
    <format>XBox</format>
</item>
  <item>
    <title>Unreal Tournament 2003</title>
    <format>CD</format>
  </item>
</items>

The comments in the above code illustrate how the functionality of this program is implemented. One thing to remember is: when calling a method starts an operation, you need to call the method to end the operation in the appropriate place in the program. For example, if you call StartElement, you must call EndElement to close the element; of course you can also add a child element between these two calls. Whenever you call the EndElement method, it always closes the element that was recently opened with the StartElement method (this is very similar to how the stack works).

Using XmlTextWriter is very easy, but I still recommend that you try these codes and methods yourself. After you try it, you will find that these codes can be easily integrated into your program. You should also remember that XmlTextWriter is just one of many XML classes provided by .NET. Like XmlTextWriter, other XML classes are also very easy to use.

 


2)
I'm using a very stupid method, but it can help beginners understand the process of accessing XML nodes.

It is known that there is an XML file () as follows:

Copy the codeThe code is as follows:

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
</bookstore>

1. Insert a <book> node into the <bookstore> node:

Copy the codeThe code is as follows:

   XmlDocument xmlDoc=new XmlDocument();
   ("");
XmlNode root=("bookstore");//Find <bookstore>
XmlElement xe1=("book");//Create a <book> node
("genre","Li Zanhong");//Set the genre attribute of this node
("ISBN","2-3631-4");//Set the ISBN attribute of this node

   XmlElement xesub1=("title");
="CS from Beginner to Mastery";//Set Text Node
(xesub1);//Add to the <book> node
   XmlElement xesub2=("author");
="not yet";
   (xesub2);
   XmlElement xesub3=("price");
   ="58.3";
   (xesub3);

(xe1);//Add to the <bookstore> node
   ("");

The result is:

Copy the codeThe code is as follows:

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
<book genre="Li Zanhong" ISBN="2-3631-4">
<title>CS From Beginner to Mastery</title>
<author>Hou Jie</author>
    <price>58.3</price>
  </book>
</bookstore>

2. Modify node: Change the genre value of the node with the genre attribute value "Li Zanhong" to "update Li Zanhong", and modify the text of the child node <author> of the node to "Yasheng".

Copy the codeThe code is as follows:

XmlNodeList nodeList=("bookstore").ChildNodes;//Get all children of the bookstore node
foreach(XmlNode xn in nodeList)//Transfer all child nodes
   {
XmlElement xe=(XmlElement)xn;//Convert child node type to XmlElement type
if(("genre")=="Li Zanhong")//If the genre attribute value is "Li Zanhong"
    {
("genre","update Li Zanhong");//Then modify this property to "update Li Zanhong"

XmlNodeList nls=;//Continue to get all children of xe child nodes
foreach(XmlNode xn1 in nls)//Transaction
     {
XmlElement xe2=(XmlElement)xn1;//Conversion type
if(=="author")//If found
      {
="Yasheng";//Then modify
break;//Just find and exit
      }
     }
     break;
    }
   }

("");//Save.

The final result is:

Copy the codeThe code is as follows:

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book genre="fantasy" ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
<book genre="updateLi Zanhong" ISBN="2-3631-4">
<title>CS From Beginner to Mastery</title>
<author>Asia Victor</author>
    <price>58.3</price>
  </book>
</bookstore>

3. Delete the genre attribute of the <book genre="fantasy" ISBN="2-3631-4"> node, and delete the <book genre="updateLi Zanhong" ISBN="2-3631-4"> node.

Copy the codeThe code is as follows:

XmlNodeList xnl=("bookstore").ChildNodes;

   foreach(XmlNode xn in xnl)
   {
    XmlElement xe=(XmlElement)xn;
    if(("genre")=="fantasy")
    {
("genre");//Delete the genre attribute
    }
else if(("genre")=="updateLi Zanhong")
    {
();//Delete all contents of this node
    }
   }
   ("");

The final result is:

Copy the codeThe code is as follows:

<?xml version="1.0" encoding="gb2312"?>
<bookstore>
  <book ISBN="2-3631-4">
    <title>Oberon's Legacy</title>
    <author>Corets, Eva</author>
    <price>5.95</price>
  </book>
  <book>
  </book>
</bookstore>

4. Display all data.

Copy the codeThe code is as follows:

 XmlNode xn=("bookstore");

   XmlNodeList xnl=;

   foreach(XmlNode xnf in xnl)
   {
    XmlElement xe=(XmlElement)xnf;
(("genre"));//Display attribute value
    (("ISBN"));

    XmlNodeList xnf1=;
    foreach(XmlNode xn2 in xnf1)
    {
();//Show child node point text
    }
   }