SoFunction
Updated on 2025-03-06

In-depth analysis of XmlWriter writing to Xml in C#


using System;
using ;
using ;
using ;
using ;

namespace UseXmlWriter
{
    class Program
    {
        static void Main(string[] args)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                XmlWriterSettings settings = new XmlWriterSettings();
//Required to be indented
                = 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, add 4 bytes of non-xml content to the front of the output text.
                = new UTF8Encoding(false);

//Set newline characters
                = ;

                using (XmlWriter xmlWriter = (ms, settings))
                {

//Start writing an xml file<?xml version="1.0" encoding="utf-8" ?>
                    (false);
//Write the root node
                    ("root");
//Writing node
                    ("cat");
//Add attributes to nodes
                    ("color", "white");
//Add text to the node inside
                    ("I'm a cat");
                    ();

 
//WriteElementString can add a node and add node content at the same time
                    ("pig", "pig is great");

 
                    ("dog");
//Writing CData
                    ("<strong>dog is dog</strong>");
                    ();

                    ("this is an example writed by  https:// ");

                    ();
                    ();

                }

//Output xml content to the console
                string xml = Encoding.(());
                (xml);
            }
            ();

        }
    }
}