XmlWriter is a forward-only writer of an XML stream. The XmlWriter is symmetrical to XmlReader.
You construct an XmlWriter by calling Create with an optional settings object.
In the following example, we enable indenting to make the output more human-readable, and then write a simple XML file:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using System.IO;
class Program
{
static void Main()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create("foo.xml", settings))
{
writer.WriteStartElement("customer");
writer.WriteElementString("firstname", "Jack");
writer.WriteElementString("lastname", "Smith");
writer.WriteEndElement();
}
}
}
The content of foo.xml
Jack
Smith
XmlWriter automatically escapes characters that would otherwise be illegal within an attribute or element, such as & < >, and extended Unicode characters.