SoFunction
Updated on 2025-03-08

C# Use XmlReader and XmlWriter to operate XML files

1. Overview

1. XMLReader is an abstract class, and its derived classes are:

  • XmlDictionaryReader
  • XmlNodeReader
  • XmlTextReader(Used with TextReader objects in IO namespace)
  • XmlValidatingReader(Added DTD and schema verification to provide validity verification of data).
•XmlReader reader =new XmlTextReader(xmlFile);
•XmlReader reader =new XmlNodeReader(xmNode);

2. XMLWriter is an abstract class, and its derived classes include

  • XmlTextWriter
  • XmlQueryWriter

2. XmlReader

1. Overview

When reading XmlDocument and XElement, the entire Xml document must be placed in memory to operate. This is easy to operate, but it costs a lot of memory. In some scenarios, we must consider saving memory as much as possible, and at this time we shouldXmlReaderandXmlWriterAppeared.

XmlReader is very similar to SAX. The biggest difference between them is that SAX is a push model (all XML data must be processed by the application, whether it is needed or not), and XmlReader is a pull model (if all the data is not needed, they are not processed).

XmlReader needs to read the Xml through the Read() instance method to continuously read the declarations in the Xml document, node start, node content, node end, and blank space, etc. until the document ends, and the Read() method returns false.

2. Common usage

(1) Use the static method Create() to return an XmlReader object.

(2) The Read() method can enter the next node. The XmlReader class can also read strongly typed data. It has several ReadValuesAs methods, such as ReadValueAsDouble, ReadValueAsBoolean, etc.

(3) Obtain attribute data:AttributeCountryAttributes determine the number of attributes.GetAttributeThe () method obtains attributes according to name or index. If you want to iterate one attribute at a time, you can use the MoveToFirstAttribute() and MoveToNextAttribute() methods.

XmlReader tr = ("");
while (()){
if ( == ){
   for (int i = 0; i < ; i++){
     ((i)+"\r\n");
     }
   }
}

3. Use the XmlReader class to verify

Sometimes you should not only know whether the format of the document is standardized, but also make sure that the document is valid.

XmlReader can use XmlReaderSettings to verify XML according to XSD schema.

XSD schema is added to XMLSchemaSet, and the XMLSchemaSet can be accessed through the Schema attribute. The XsdValidate property must also be set to ture, which defaults to flase.

XmlReaderSettings settings = new XmlReaderSettings();
 = true;
 = true;
XmlReader reader = ("", settings);//settings parameter is optional.List lists = new List();
CustomerInfo cust = null;

while (())//Read the next node{
    if ( == )
    {
        switch ()
        {
            case "row":
                cust = new CustomerInfo();
                if ()//Because attributes are not part of the document structure, you need to check it specifically.  Whether the property HasValue has a value; IsEmptyElement: Is it an empty element                {
                     = ("AppID");
                     = ("Version");
                }
                break;

            case "CustomerID":
                 = ();
                break;

            case "CompanyName":
                 = ();
                break;
            default:
                break;

        }
    }
}

4. Read byte data BinHex

The following example reads an inline BinHex encoded image. BinHex data is embedded in the element. BinaryWriter is used to create a new binary data file.

public static void BinHexDecodeImageFile() {

  byte[] buffer = new byte[1000];
  int readBytes = 0;

  using (XmlReader reader = ("")) {
                       
        FileStream outputFile = new FileStream(@"C:\artFiles\data\", , , );
        // Read to the image element.
        ("image");
        // Read the BinHex data.
        ("\r\nReading BinHex...");
        BinaryWriter bw = new BinaryWriter(outputFile);
        while ((readBytes = (buffer, 0, 50))>0) 
        {
            (buffer, 0, readBytes);
        }
        ();
        
  }
}

3. XmlWriter

1. Overview

Like XmlReader, the XmlWriter class writes in a forward-only, uncached way.

2. Common usage

1. Write an Xml document statement

WriteStartDocument method can accept a bool parameter (representing standalone, whether it is a standalone or not specified to maintain the default value.

(false|true);

Note that it is best to call the() method after using the WriteStartDocument method to close all possible tags that are not closed.

2. Write xml nodes and properties

//Write node("cat");

//Add attributes to node("color", "white");

//Add text to the node inside("I'm a cat");
(); 

// Or write the xml node through WriteElementString(string, string) method and write the node value at the same time, as follows("pig", "pig is great");

3. Write CData

("dog is dog");

4. If you add comments

("*** ");

5. How to set the output format of XmlWriter to solve the output UTF-16 problem

Setting the xml output format requires the XmlWriterSettings class, as follows

XmlWriterSettings settings = new XmlWriterSettings();

//Required to indent = true;

//Note that if encoding is not set, the default output will be utf-16 //Note that you cannot use Encoding.UTF8 directly here. If you use Encoding.UTF8, you will add 4 bytes of non-xml content to the front of the output text. = new UTF8Encoding(false);

 //Set newline characters = ;

6. Write to other objects

The XmlWriter class can write Xml to a stream, file, StringBuilder, TextWriter, or another XmlWriter object.

7. Namespace support

XmlTextWriter w = new XmlTextWriter();
("x","root","urn:1");
("y","item","urn:1");
("abc","urn:1","xyz");
();
();
();

3. Complete code example of XmlWriter

XmlWriterSettings settings = new XmlWriterSettings();
 = true;
 = "\t";
 = false;
 = ;
 = false;

//Note that if encoding is not set, the default output will be utf-16//Note that you cannot use Encoding.UTF8 directly here. If you use Encoding.UTF8, you will add 4 bytes of non-xml content to the front of the output text. = new UTF8Encoding(false);

//Set newline characters = ;

XmlWriter writer = ("", settings);//settings parameter is optional.//Write to StringBuiler and Stream using xmlwriter://StringBuilder builder = new StringBuilder();
//XmlWriter writer = (builder, settings);
//MemoryStream stream = new MemoryStream();
//XmlWriter writer = (stream, settings);
();//Write Xml declaration: optional parameters represent standalone, whether it is an independent document("XXX"); //Write a comment("Table");//Writing complex elements (elements contain child elements)for (int i = 1; i &lt; 10; i++)
{
    ("row");
    ("Version", "2.0");
    ("AppID", "111");
    ("CustomerID", "cmz" + ());//Write simple elements    ("CompanyName", "Cheng Muzhe" + ());
    ();
}

();
();
();
();

4. Write byte data BinHex

//Use the WriteBinHex method to write BinHex data.  BinHex data is embedded in the element.int bufferSize = 1000;
byte[] buffer = new byte[bufferSize];
int readBytes = 0;

using (XmlWriter writer = (""))
{
    FileStream inputFile = new FileStream(@"C:\", ,, );
    ();
    ("image");
    BinaryReader br = new BinaryReader(inputFile);
    ("\r\nWriting BinHex data...");

    do
    {
        readBytes = (buffer, 0, bufferSize);
        (buffer, 0, readBytes);
    } while (bufferSize &lt;= readBytes);
    ();

    ();//
    ();
}

This is all about C#'s article on using XmlReader and XmlWriter to operate XML files. I hope it will be helpful to everyone's learning and I hope everyone will support me more.