ZetCode

C# XmlWriter

last modified October 18, 2026

In this article we show how to write XML data in C# with XmlWriter.

XmlWriter

XmlWriter represents a writer that provides a fast, non-cached, forward-only way to generate streams or files with XML. Because it never builds a tree in memory, it can produce very large documents with little memory. The price is that we must write the nodes in document order and cannot go back and change anything; for that, use XmlDocument.

XmlWriter is an abstract class in the System.Xml namespace. We create instances with the static Create method, which accepts a file name, a Stream, a TextWriter, or a StringBuilder, and an optional XmlWriterSettings. The writer checks that the output is well-formed XML: names must be valid, tags must nest properly, and special characters are escaped for us.

C# XmlWriter example

The following example creates a simple XML document with XmlWriter.

Program.cs
using System.Xml;

var settings = new XmlWriterSettings { Indent = true };

using (XmlWriter writer = XmlWriter.Create("data.xml", settings))
{
    writer.WriteStartDocument();

    writer.WriteStartElement("value");
    writer.WriteValue(6);
    writer.WriteEndElement();

    writer.WriteEndDocument();
}

Console.WriteLine("XML document created");
Console.WriteLine(File.ReadAllText("data.xml"));

We create a new XML document. It contains the XML declaration and a single XML element.

var settings = new XmlWriterSettings { Indent = true };

using (XmlWriter writer = XmlWriter.Create("data.xml", settings))
{

The XmlWriter is created with the Create method. We pass the name of the file and the settings to the method. With Indent set to true, the output is formatted for humans; by default, everything is written on one line. The using block closes the writer and the file. We read the file after the block, because the content is not complete until the writer has been flushed and closed.

writer.WriteStartDocument();

The WriteStartDocument method writes the XML declaration. It is optional.

writer.WriteStartElement("value");
writer.WriteValue(6);
writer.WriteEndElement();

The WriteStartElement and WriteEndElement pair adds a new element to the document. The WriteValue method writes a single simple-typed value, converted to text using XML rules.

writer.WriteEndDocument();

The WriteEndDocument method closes any open elements or attributes.

$ dotnet run
XML document created
<?xml version="1.0" encoding="utf-8"?>
<value>6</value>

When writing to a file name or a stream, XmlWriter encodes the text as UTF-8 and by default adds a byte order mark at the beginning of the file. To avoid the BOM, create the writer on a stream with Encoding = new UTF8Encoding(false) in the settings, as shown below.

C# XmlWriter books example

The following example creates an XML file with two books.

Program.cs
using System.Xml;

var settings = new XmlWriterSettings { Indent = true };

using var writer = XmlWriter.Create("books.xml", settings);

writer.WriteStartDocument();
writer.WriteStartElement("bookstore");

WriteBook(writer, "Science Fiction", "Dune", "Frank Herbert", 8.99m);
WriteBook(writer, "Novel", "Old Goriot", "Honoré de Balzac", 9.0m);

writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();

Console.WriteLine("XML document created");

static void WriteBook(XmlWriter writer, string genre, string title, string author, decimal price)
{
    writer.WriteStartElement("book");
    writer.WriteAttributeString("genre", genre);

    writer.WriteElementString("title", title);
    writer.WriteElementString("author", author);
    writer.WriteStartElement("price");
    writer.WriteValue(price);
    writer.WriteEndElement();

    writer.WriteEndElement();
}

In addition to elements, we also create attributes with WriteAttributeString. The repetitive part is moved into a helper method.

writer.WriteStartElement("book");
writer.WriteAttributeString("genre", genre);

Attributes must be written right after WriteStartElement, before any content. Writing an attribute after the content has started is an error.

writer.WriteElementString("title", title);

The WriteElementString method is a shortcut that writes the start tag, the text, and the end tag of a simple element.

writer.WriteStartElement("price");
writer.WriteValue(price);
writer.WriteEndElement();

The WriteValue method accepts typed values such as decimals, dates and booleans and formats them the way XML schema requires, independent of the current culture.

$ dotnet run
XML document created
$ cat books.xml
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
  <book genre="Science Fiction">
    <title>Dune</title>
    <author>Frank Herbert</author>
    <price>8.99</price>
  </book>
  <book genre="Novel">
    <title>Old Goriot</title>
    <author>Honoré de Balzac</author>
    <price>9.0</price>
  </book>
</bookstore>

C# XmlWriter products example

The next example creates an XML file from a list of objects.

Program.cs
using System.Xml;

var products = new List<Product>
{
    new(1, "Product A", 12.2M),
    new(2, "Product B", 11.3M),
    new(3, "Product C", 9M),
    new(4, "Product D", 5.6M),
    new(5, "Product E", 11.7M)
};

var settings = new XmlWriterSettings { Indent = true };

using (var writer = XmlWriter.Create("products.xml", settings))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("products");

    foreach (var product in products)
    {
        writer.WriteStartElement("product");
        writer.WriteElementString("id", product.Id.ToString());
        writer.WriteElementString("name", product.Name);
        writer.WriteElementString("price", XmlConvert.ToString(product.Price));
        writer.WriteEndElement();
    }

    writer.WriteEndElement();
    writer.WriteEndDocument();
}

Console.WriteLine(File.ReadAllText("products.xml"));

record Product(int Id, string Name, decimal Price);

We have a list of products created with the C# record type. We go over the list and generate an XML file from the objects.

writer.WriteElementString("price", XmlConvert.ToString(product.Price));

The WriteElementString method takes strings. For numbers, dates, and other types, XmlConvert.ToString gives the invariant XML representation. Calling plain ToString would use the current culture, which in some cultures writes a decimal comma.

$ dotnet run
<?xml version="1.0" encoding="utf-8"?>
<products>
  <product>
    <id>1</id>
    <name>Product A</name>
    <price>12.2</price>
  </product>
  <product>
    <id>2</id>
    <name>Product B</name>
    <price>11.3</price>
  </product>
  <product>
    <id>3</id>
    <name>Product C</name>
    <price>9</price>
  </product>
  <product>
    <id>4</id>
    <name>Product D</name>
    <price>5.6</price>
  </product>
  <product>
    <id>5</id>
    <name>Product E</name>
    <price>11.7</price>
  </product>
</products>

C# XmlWriter to a string or a stream

The writer can target a StringBuilder, a TextWriter, or a Stream. The destination decides how the encoding is handled.

Program.cs
using System.Text;
using System.Xml;

var settings = new XmlWriterSettings
{
    Indent = true,
    IndentChars = "    ",
    OmitXmlDeclaration = true
};

// the encoding of a StringWriter is UTF-16, which ends up in the declaration
var sw = new StringWriter();
using (var writer = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true }))
{
    writer.WriteStartDocument();
    writer.WriteElementString("a", "text");
}
Console.WriteLine(sw);

// without the declaration, the problem does not exist
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb, settings))
{
    writer.WriteStartElement("root");
    writer.WriteElementString("a", "text");
    writer.WriteEndElement();
}
Console.WriteLine(sb);

// to a stream, with an encoding
var ms = new MemoryStream();
using (var writer = XmlWriter.Create(ms, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))
{
    writer.WriteElementString("a", "žltý");
}
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));

The program writes XML to a StringWriter, a StringBuilder, and a memory stream.

var sw = new StringWriter();
using (var writer = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true }))

A StringWriter reports UTF-16 as its encoding, so the declaration says encoding="utf-16", although the string itself is not encoded at all. If we save such a string to a file as UTF-8, the declaration lies. Use OmitXmlDeclaration = true when producing a string, or write to a stream.

var settings = new XmlWriterSettings
{
    Indent = true,
    IndentChars = "    ",
    OmitXmlDeclaration = true
};

Here we also use four spaces instead of the default two for indentation, and leave out the declaration.

using (var writer = XmlWriter.Create(ms, new XmlWriterSettings { Encoding = new UTF8Encoding(false) }))

For streams, the Encoding setting decides how the characters are encoded. new UTF8Encoding(false) is UTF-8 without a byte order mark.

$ dotnet run
<?xml version="1.0" encoding="utf-16"?>
<a>text</a>
<root>
    <a>text</a>
</root>
<?xml version="1.0" encoding="utf-8"?><a>žltý</a>

C# XmlWriter escaping, CDATA and comments

The writer escapes characters that have a special meaning in XML. We can also write comments and CDATA sections, which hold text without escaping.

Program.cs
using System.Xml;

var settings = new XmlWriterSettings { Indent = true };
using var writer = XmlWriter.Create(Console.Out, settings);

writer.WriteStartDocument();
writer.WriteComment(" special characters ");
writer.WriteStartElement("data");

writer.WriteAttributeString("expr", "a < b & \"c\"");
writer.WriteElementString("text", "1 < 2 && 3 > 2");
writer.WriteStartElement("code");
writer.WriteCData("if (a < b && c > d) { }");
writer.WriteEndElement();
writer.WriteElementString("empty", "");
writer.WriteStartElement("selfclosing");
writer.WriteEndElement();
writer.WriteElementString("unicode", "žltý kôň €");

writer.WriteEndElement();
writer.WriteEndDocument();

The program writes text with special characters in several ways.

writer.WriteAttributeString("expr", "a < b & \"c\"");
writer.WriteElementString("text", "1 < 2 && 3 > 2");

We pass plain text, and the writer replaces <, &, and > in text and the quotes in attribute values with entities. We never escape the text by hand, as that would produce double escaping.

writer.WriteCData("if (a < b && c > d) { }");

In a CDATA section, nothing needs to be escaped. The only forbidden text is the sequence ]]>.

$ dotnet run
<?xml version="1.0" encoding="utf-8"?>
<!-- special characters -->
<data expr="a &lt; b &amp; &quot;c&quot;">
  <text>1 &lt; 2 &amp;&amp; 3 &gt; 2</text>
  <code><![CDATA[if (a < b && c > d) { }]]></code>
  <empty />
  <selfclosing />
  <unicode>žltý kôň €</unicode>
</data>

Elements without content are written as self-closing tags, whether we wrote an empty string or nothing at all. Non-ASCII characters are written as they are, because the encoding is UTF-8.

C# XmlWriter namespaces

The writer supports XML namespaces. The overloads of the write methods accept a prefix and a namespace URI, and the writer declares the namespaces where needed.

Program.cs
using System.Xml;

var settings = new XmlWriterSettings
{
    Indent = true,
    NewLineOnAttributes = true,
    OmitXmlDeclaration = true
};

const string ns = "http://example.com/orders";
const string meta = "http://example.com/meta";

using var writer = XmlWriter.Create(Console.Out, settings);

writer.WriteStartElement("o", "orders", ns);
writer.WriteAttributeString("xmlns", "m", null, meta);
writer.WriteAttributeString("m", "version", meta, "2");

writer.WriteStartElement("order", ns);
writer.WriteAttributeString("id", "1001");
writer.WriteElementString("item", ns, "keyboard");
writer.WriteEndElement();

writer.WriteEndElement();

We write an order document with a default-prefixed namespace and a second namespace for an attribute. The NewLineOnAttributes setting puts each attribute on its own line.

writer.WriteStartElement("o", "orders", ns);

The first argument is the prefix, the second the local name, and the third the namespace URI. The writer adds the xmlns:o declaration to the element automatically.

writer.WriteAttributeString("xmlns", "m", null, meta);
writer.WriteAttributeString("m", "version", meta, "2");

We declare the prefix m explicitly and then use it for an attribute. Child elements written with the same namespace URI reuse the existing prefix.

$ dotnet run
<o:orders
  xmlns:m="http://example.com/meta"
  m:version="2"
  xmlns:o="http://example.com/orders">
  <o:order
    id="1001">
    <o:item>keyboard</o:item>
  </o:order>
</o:orders>

C# XmlWriter async

When the destination is a network stream or slow storage, we can write asynchronously. The settings must have Async set to true.

Program.cs
using System.Xml;

var settings = new XmlWriterSettings { Async = true, Indent = true };

await using (var writer = XmlWriter.Create("async.xml", settings))
{
    await writer.WriteStartDocumentAsync();
    await writer.WriteStartElementAsync(null, "numbers", null);

    for (int i = 1; i <= 3; i++)
    {
        await writer.WriteElementStringAsync(null, "n", null, i.ToString());
    }

    await writer.WriteEndElementAsync();
    await writer.WriteEndDocumentAsync();
}

Console.WriteLine(await File.ReadAllTextAsync("async.xml"));

The example writes a small document asynchronously.

await using (var writer = XmlWriter.Create("async.xml", settings))
{
    await writer.WriteStartDocumentAsync();
    await writer.WriteStartElementAsync(null, "numbers", null);

Every write method has an asynchronous counterpart. Note that the asynchronous methods do not have the shortened overloads; we pass the prefix and the namespace explicitly, as null here. await using disposes the writer asynchronously.

$ dotnet run
<?xml version="1.0" encoding="utf-8"?>
<numbers>
  <n>1</n>
  <n>2</n>
  <n>3</n>
</numbers>

C# XmlWriter errors and conformance

The writer enforces well-formed XML and throws exceptions when we try to produce something invalid.

Program.cs
using System.Xml;

try
{
    using var writer = XmlWriter.Create(Console.Out);

    writer.WriteStartElement("bad name");     // spaces are not allowed in names
}
catch (ArgumentException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

try
{
    using var writer = XmlWriter.Create(TextWriter.Null);

    writer.WriteStartElement("a");
    writer.WriteEndElement();
    writer.WriteStartElement("b");           // a second root element
}
catch (InvalidOperationException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

// control characters that XML 1.0 forbids are rejected unless we relax the check
try
{
    using var writer = XmlWriter.Create(TextWriter.Null);
    writer.WriteElementString("a", "bad \u0001 char");
}
catch (ArgumentException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message}");
}

var lenient = new XmlWriterSettings { CheckCharacters = false, ConformanceLevel = ConformanceLevel.Fragment };
using (var writer = XmlWriter.Create(TextWriter.Null, lenient))
{
    writer.WriteElementString("a", "ok");
    writer.WriteElementString("b", "two roots allowed in a fragment");
}
Console.WriteLine("fragment written");

The program provokes three different errors and then writes an XML fragment.

writer.WriteStartElement("bad name");

Names must be valid XML names, so a space is rejected with an ArgumentException.

writer.WriteStartElement("a");
writer.WriteEndElement();
writer.WriteStartElement("b");

A document has only one root element. Writing a second one throws an InvalidOperationException. With ConformanceLevel.Fragment in the settings, multiple top-level elements are allowed, which is useful for logs and message streams.

writer.WriteElementString("a", "bad \u0001 char");

Control characters other than tab, line feed and carriage return are illegal in XML 1.0. The writer refuses them unless CheckCharacters is false, in which case the result may not be readable by other XML parsers.

$ dotnet run
ArgumentException: Invalid name character in 'bad name'. The ' ' character, hexadecimal value 0x20, cannot be included in a name.
InvalidOperationException: Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment.
ArgumentException: '', hexadecimal value 0x01, is an invalid character.
fragment written

C# XmlWriter and XmlReader together

A common task is to transform a document while copying it. With a reader and a writer, this works in a streaming way, however big the document is.

Program.cs
using System.Xml;

// copy an XML document from a reader to a writer, changing only what we need
string xml = "<items><item price=\"10\">a</item><item price=\"20\">b</item></items>";

var rs = new XmlReaderSettings { IgnoreWhitespace = true };
using var reader = XmlReader.Create(new StringReader(xml), rs);
using var writer = XmlWriter.Create(Console.Out, new XmlWriterSettings { Indent = true });

while (reader.Read())
{
    switch (reader.NodeType)
    {
        case XmlNodeType.Element:
            writer.WriteStartElement(reader.Name);

            while (reader.MoveToNextAttribute())
            {
                string value = reader.Name == "price"
                    ? (int.Parse(reader.Value) * 2).ToString()    // double the price
                    : reader.Value;
                writer.WriteAttributeString(reader.Name, value);
            }

            reader.MoveToElement();

            if (reader.IsEmptyElement)
            {
                writer.WriteEndElement();
            }
            break;
        case XmlNodeType.Text:
            writer.WriteString(reader.Value);
            break;
        case XmlNodeType.EndElement:
            writer.WriteEndElement();
            break;
    }
}

The program copies a document and doubles the value of every price attribute.

while (reader.MoveToNextAttribute())
{
    ...
    writer.WriteAttributeString(reader.Name, value);
}

reader.MoveToElement();

We copy the attributes one by one, changing the ones we are interested in, and return the reader to the element. An empty element has no end-tag node, so we close it ourselves. For an unmodified copy, the WriteNode method of the writer copies a whole node and its children from a reader in one call.

$ dotnet run
<?xml version="1.0" encoding="utf-8"?>
<items>
  <item price="20">a</item>
  <item price="40">b</item>
</items>

Source

XmlWriter class

In this article we have written XML data with XmlWriter.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.