Skip to main content
Utf8XmlWriter is a forward-only writer for UTF-8 encoded XML. You call a method for each start tag, attribute, value, and end tag, and the writer produces the bytes, escapes what needs escaping, declares namespaces, and checks that the result is well formed. This article shows how to use it. Use the writer when you produce XML by hand, when the output is too large to build as a tree first, or when you write a custom converter. To write your own types as XML, use XmlSerializer. To build or edit a tree, use XmlNode. If you know Utf8JsonWriter from System.Text.Json, the shape is the same: a class that writes to an IBufferWriter<byte> or a Stream, with WriteStart* and WriteEnd* methods, typed value methods, Flush, Reset, and options in a struct.

Write to a buffer

Create the writer over an IBufferWriter<byte>, such as an ArrayBufferWriter<byte> or a PipeWriter, and dispose it when the document is complete. Every element is a WriteStartElement call, then its attributes, then its content, then WriteEndElement.
The code produces the following output:
View the complete sample on GitHub What to notice:
  • The writer adds the XML declaration. It writes it before the first element unless you turn it off.
  • A start tag stays open until you write content or end the element. Attributes go in that window. Writing an attribute after the element has content throws an XmlException.
  • WriteEndElement takes no name. The writer knows which element is open. An element with no content, like Notes, is closed as an empty element.
  • Disposing the writer finishes the document. It flushes the output. If an element is still open, it throws instead. See Validation.
  • The output is bytes. The sample decodes them to print them. In an application, send buffer.WrittenSpan or buffer.WrittenMemory where the XML is going.
Most methods take names and values as a string, as a ReadOnlySpan<char>, or as UTF-8 in a ReadOnlySpan<byte>, such as a u8 literal, and element names also as an XmlEncodedText. The UTF-8 overloads skip the transcoding step. A few methods, such as WriteAttributeNumber and WriteProcessingInstruction, take only string.

Write to a stream

Pass a Stream instead, and the writer collects output in a buffer rented from the array pool and writes it to the stream when the buffer fills and when you flush.
The code produces the following output:
View the complete sample on GitHub Disposing the writer flushes the stream and returns the rented buffer. It doesn’t close or dispose the stream, so the stream stays yours to use. The output isn’t indented here because the sample uses the default options.

Write typed values

A value method writes one value where the writer is: inside the element that’s open, or inside an attribute that you opened with WriteStartAttribute. The methods format .NET values in the lexical forms of XML Schema, with the invariant culture, so that any XML tool reads them the same way.
The code produces the following output:
View the complete sample on GitHub The typed methods of Utf8XmlReader read every one of these forms back. WriteAttributeNumber takes an int, a long, or a double. For an attribute of any other type, do as the sample does for insured: open the attribute with WriteStartAttribute, call a value method, and close it with WriteEndAttribute. Call a value method more than once in the same element and the values are written one after the other, as one run of text. To write one value from several buffers, use WriteStringValueSegment or WriteBase64StringSegment and pass isFinalSegment: true with the last buffer. The output is the same as one call with the whole value, wherever you cut:
  • A text segment can end in the middle of a multi-byte UTF-8 character, or between the two halves of a surrogate pair. The writer keeps the incomplete character and writes it when the next segment completes it.
  • A binary segment can be any length. The writer pads the Base64 text only at the end of the value, so two segments of one byte each produce AQI=.
After a segment that isn’t final, the next write must be the next segment of the same kind. You can call Flush or FlushAsync between segments. Any other Write* call throws XmlException.

Write a complete element in one call

Most elements hold one value. For those, a WriteElement* method writes the start tag, the value, and the end tag together.
The code produces the following output:
View the complete sample on GitHub To choose between the two ways of closing an element:
  • WriteEndElement writes </Notes> when the element has content. When it has none, the element is written in the form EmptyElementStyle asks for, which is <Notes/> by default.
  • WriteFullEndElement always writes the end tag, so an element with no content becomes <Notes></Notes>, whatever EmptyElementStyle is. Use it for consumers that treat the two forms differently, such as HTML parsers.
WriteEmptyElement and WriteElementString with a null string follow EmptyElementStyle too. See Control the layout.

Pass the name as bytes, characters, or an encoded name

Every WriteElement* method takes the name of the element as a string, a ReadOnlySpan<char>, a ReadOnlySpan<byte> of UTF-8, or an XmlEncodedText, as the Write* methods of Utf8JsonWriter take a property name. WriteElementString takes its text in the same three forms. Each form writes the same element.
The code produces the following output:
View the complete sample on GitHub What to notice:
  • A u8 literal or an XmlEncodedText is already UTF-8, so the writer copies the name without converting it.
  • A null literal for the text doesn’t say which overload you mean, and the call doesn’t compile. Cast it, as (string?)null in the sample, or pass a string variable. Utf8JsonWriter.WriteString has the same rule.

How the writer escapes values

You pass values as they are. The writer escapes the characters that would otherwise change meaning or be changed by a reader, so a value is read back exactly as you wrote it.
The code produces the following output:
View the complete sample on GitHub What to notice in the output:
  • > is left alone except in ]]>, and " is left alone in element text. Both are legal there.
  • The white space in the attribute is written as character references. A reader replaces a literal tab or line end in an attribute with a space, so a reference is the only way to keep it.
  • The carriage return in the text is a reference for the same reason: a reader turns a literal one into a line feed.
  • The line feed in the text is a line break in the output, and the writer writes every line break as the NewLine option says. The sample sets NewLine to "\n". With "\r\n" the text is still read back unchanged, because a reader gives a carriage return and a line feed back as one line feed.
A character that XML doesn’t allow at all, such as U+0000, can’t be escaped, and writing it throws Illegal character in XML value. XML 1.1 allows more characters than XML 1.0.

Write namespaces

To put an element or an attribute in a namespace, pass the namespace URI. You don’t write xmlns attributes yourself unless you want to choose where they go. The writer tracks which namespaces are in scope and declares what’s missing.
The code produces the following output:
View the complete sample on GitHub The rules the writer follows: A declaration ends with the element it’s on. That’s why s had to be generated again as ns1 on entry: the s prefix was declared on s:order and went out of scope with it. To avoid repeated declarations, declare the prefixes you need on the root element, as the sample does with dc.
An element that you write without a namespace argument, such as WriteStartElement("title"), gets no prefix and no declaration. Under a default namespace, a reader therefore puts it in that default namespace. A null namespace argument means the same. To take an element out of the default namespace, pass an empty string as its namespace: WriteStartElement("title", "") writes <title xmlns="">.
The writer rejects declarations that Namespaces in XML forbids: binding the xmlns prefix, binding xml to any namespace but its own, binding another prefix to either reserved namespace or making one of them the default namespace, and, in XML 1.0, xmlns:p="". For namespaces in the serializer, see Namespaces.

The XML declaration

By default, the writer starts the document with <?xml version="1.0" encoding="utf-8"?>. Four options change that.
WriteOrder writes one empty element with the options it’s given:
The code produces the following output:
View the complete sample on GitHub The encoding is always utf-8, because that’s the only encoding the writer produces. The writer writes the declaration by itself, before the first element, comment, or processing instruction. WriteXmlDeclaration writes it at a moment you choose, and it does so even when OmitXmlDeclaration is true. It must be the first thing you write. After any other output it throws The XML declaration must be the first output.

Indent the output

By default, the writer adds no white space, which gives the smallest output. Set Indented to put each element on its own line.
WriteParagraph writes an element that has only child elements and an element that mixes text with a child:
The code produces the following output:
View the complete sample on GitHub Indentation never changes a value. An element that holds text, such as Note, is written on one line, child elements included, because white space next to text is part of the content. The writer indents only between elements.
NewLine defaults to the line ending of the machine that runs the code, so the same program writes different bytes on Windows and on Linux. Set it to "\n" or "\r\n" when the output is compared, hashed, signed, or checked in.

Control the layout

These options set how the markup is laid out. None of them changes what a reader gets from the document. Each is a rule for the whole output, whichever code wrote it: your calls, the serializer, or a document or node that writes itself.

Choose the form of an empty element

EmptyElementStyle applies to an element that you end with WriteEndElement before you write any content, to WriteEmptyElement, and to WriteElementString with a null string.
The code produces the following output:
View the complete sample on GitHub WriteFullEndElement writes an end tag under every setting. Indentation puts nothing between the two tags of <b></b>, because white space there would be content.

Put attributes on their own lines

With AttributeStyle = XmlAttributeStyle.PerLine, the writer breaks the line between attributes. Each line after the first starts with the white space that starts the line of the tag, then one space for each character of the tag up to its first attribute. For a tag that starts its line, that puts the attributes under the first one. The sample writes one document twice: with one attribute to a line, and then with AttributesPerLine = 2.
The code produces the following output:
View the complete sample on GitHub
  • A namespace declaration and xsi:nil are attributes and are counted.
  • PerLine works with or without Indented.
  • AttributesPerLine can’t be negative. A negative value throws ArgumentOutOfRangeException.

Choose the line ending

NewLine is written for every line break in the output: the ones Indented and PerLine add, and the ones inside text, CDATA sections, comments, and processing instructions. A document therefore has one kind of line ending, whatever it was read with.
The code produces the following output:
View the complete sample on GitHub
  • The property accepts "\n" and "\r\n", the two values JsonWriterOptions.NewLine accepts in System.Text.Json. Any other string throws ArgumentOutOfRangeException, and null throws ArgumentNullException. The default is Environment.NewLine.
  • No value changes. A reader gives a carriage return followed by a line feed back as one line feed, so the text of r is read back as "a\nb".
  • A carriage return that is part of a value is still written as &#xD;, and a line feed in an attribute value is still written as &#xA;. See How the writer escapes values.
  • A document that was read with LF line ends is written with CRLF on Windows unless you set NewLine = "\n".

Write comments, CDATA, processing instructions, and raw XML

Each of these has its own method.
The code produces the following output:
View the complete sample on GitHub What to notice:
  • Comments and processing instructions are indented like elements. With Indented set, each gets a line of its own, unless the element it’s in holds text.
  • A CDATA section isn’t escaped. That’s its purpose. Like text, it keeps its element on one line.
  • Raw XML inside an element counts as text of that element. The writer doesn’t indent inside it, so Address stays on one line. At the document level, raw XML doesn’t make the writer write the XML declaration first.
  • The text of a comment isn’t padded. Include the spaces you want inside the delimiters.
WriteRawValue copies your input to the output without escaping it. By default the writer first reads the input and throws XmlException if the document wouldn’t be well formed with it: inside an element the input must be element content that uses only prefixes in scope, in an attribute it must be an attribute value, and at the document level it can hold at most the one root element. That check costs a second pass over the input. If you pass skipInputValidation: true, or the writer has SkipValidation set, nothing is checked, and input that isn’t well-formed XML makes a document that isn’t either. Being well formed doesn’t make input safe: never pass text that came from a user or from another system.

Write XML 1.1

XML 1.0 has no way to write most control characters. If your data can contain them, set Version to XmlVersion.Version11. The writer then writes them as character references, and the declaration says version="1.1" so that a reader applies the same rules.
The code produces the following output:
View the complete sample on GitHub Choose XML 1.1 only when you need it. Many XML tools read XML 1.0 only. Utf8XmlReader and XmlDocument read both. U+0000 isn’t allowed in either version.

Encode names you write often

Each time you pass a name as a string, the writer converts it to UTF-8. For a name that you write many times, do the conversion once: create an XmlEncodedText and keep it in a static field. This is the counterpart of JsonEncodedText.
The code produces the following output:
View the complete sample on GitHub What to know:
  • Encode takes a string, a ReadOnlySpan<char>, or UTF-8 bytes, and copies them.
  • Encoding doesn’t check the name. The writer checks it each time it writes it, unless validation is off, and an element written with an XmlEncodedText name is the same element as one written with the name as a string.
  • XmlEncodedText is for element names with no prefix and no namespace argument: WriteStartElement, WriteEmptyElement, WriteNilElement and every WriteElement* method have an overload for it. Like WriteStartElement("Item"), they declare no namespace for the element, so under a default namespace the element is in that namespace. For attribute names, and for an element with a prefix or a namespace argument, pass a u8 literal (as "Items"u8 in the sample): it’s UTF-8 already, so it needs no conversion and no field.
  • It’s for names only. A name is never escaped, so don’t use it to carry text.

Flush and dispose

The writer doesn’t hand each byte to the output as you write it. Bytes are pending until the writer commits them, and two properties tell you where things stand:
  • BytesPending is the number of bytes written but not yet committed.
  • BytesCommitted is the number of bytes committed since the writer was created or reset.
Flush commits what’s pending. With an IBufferWriter<byte>, that makes the bytes visible in the buffer. With a Stream, it writes them to the stream and flushes the stream.
The code produces the following output:
View the complete sample on GitHub Until you flush, the buffer is empty: reading buffer.WrittenSpan before Flush or Dispose is the most common mistake with this writer. You can flush in the middle of a document, as the sample does, and what’s committed is everything written so far. The writer also commits by itself when it runs out of room, so pending bytes don’t pile up as the document grows. You don’t need to flush to keep memory down. Flush when a consumer is waiting for the bytes.

Flush asynchronously

With a stream that does real I/O, use FlushAsync and await using, so that no thread blocks while the bytes go out. The Write* methods themselves are synchronous: they only fill the writer’s buffer.
The code produces the following output:
View the complete sample on GitHub
When the writer’s buffer fills between your calls to FlushAsync, the writer writes to the stream synchronously. To keep all I/O asynchronous, call FlushAsync often enough that the buffer, which starts at 16 KB, doesn’t fill. FlushAsync takes a CancellationToken.
Dispose and DisposeAsync flush, and then return the writer’s rented buffers. After that, the Write* methods, Flush, and Reset throw an ObjectDisposedException. Disposing twice is safe.

Reuse a writer

Creating a writer allocates. Reset puts an existing writer back to its starting state so that it can write another document with the same options, and it keeps the buffers the writer has already grown.
The code produces the following output:
View the complete sample on GitHub Reset discards bytes that are still pending, as Utf8JsonWriter.Reset does, so a document that was abandoned half-way doesn’t reach the output. Call Flush first to keep what was written, as the loop above does. What Reset does and doesn’t do:
  • It sets BytesCommitted and the depth to 0 and forgets the namespaces in scope. The next document gets its own XML declaration, unless OmitXmlDeclaration is set.
  • It keeps the options. To write with different options, create another writer.
  • It doesn’t clear your output. The sample resets the ArrayBufferWriter<byte> itself.
  • It doesn’t check that the previous document was complete. That check belongs to Dispose.
A reused writer allocates nothing per document, and an allocation test in the library’s test suite holds that in place. System.Xml.XmlWriter has no reset, so each document needs a new one: it takes 33.4 µs and 13,728 bytes to write a catalog of 200 items that a reused Utf8XmlWriter writes in 16.4 µs. See Benchmarks for the measurements.
A writer isn’t thread safe. Reuse one from a single thread at a time, for example one writer per thread or per pooled worker. See Thread safety.

Validation

The writer checks what you write and throws an XmlException as soon as a call would make the document not well formed.
Try runs the calls against a new writer and returns the message of the exception:
The code produces the following output:
View the complete sample on GitHub The last line is the one to remember: Dispose throws when an element is still open, after it has flushed what was written. The writer never closes elements for you, because a document that was cut short shouldn’t look complete. The writer throws three kinds of exception:

An error inside a using statement

When a call throws in the middle of a document, elements are still open. If the writer is in a using statement, Dispose then runs, throws its own exception about the unclosed elements, and that exception replaces the first one.
The code produces the following output:
View the complete sample on GitHub
The message you catch is from Dispose, not from the call that failed (Invalid XML name.). The same happens when your own code throws between two writer calls. When you debug a writer, look for the first exception, or catch inside the using block. Dispose flushes before it throws, so the output holds the part of the document written before the failure. Discard the output when writing fails.

Skip validation

When you’re certain that your code writes correct XML, SkipValidation turns most checks off.
The code produces the following output:
View the complete sample on GitHub The writer accepted a duplicate attribute and a name that isn’t a name, and produced output that no XML reader accepts. Leave validation on unless a measurement shows that you need it off.

Limits

Three limits guard against output that grows without bound, for example when you write a graph of objects that’s deeper than you expected. Exceeding one throws an XmlException whose message names the option.
The code produces the following output:
View the complete sample on GitHub A value of 0 selects the default. No value turns a limit off; you can only raise it. SkipValidation skips the MaxNameByteCount check along with the name checks, and leaves the other two in force. The defaults match those of Utf8XmlReader, so a document the writer produces with default options is one the reader accepts with default options. The writer has no limit on the length of text or of the document, because you supply both.

What the writer doesn’t support

  • Encodings other than UTF-8. To produce another encoding, transcode the output, for example with Encoding.CreateTranscodingStream, and write the declaration yourself.
  • Document type declarations and entity references. There’s no method for either. WriteRawValue can write them, unchecked, but Utf8XmlReader doesn’t read a document that has a DTD.
  • Asynchronous Write* methods. Writing fills a buffer, and only FlushAsync and DisposeAsync do I/O.
  • Closing elements for you. There’s no method that ends every open element, and Dispose doesn’t.
  • Namespaced attributes from span names. WriteAttributeString(ReadOnlySpan<byte>, ReadOnlySpan<byte>), WriteAttributeString(ReadOnlySpan<char>, ReadOnlySpan<char>), and WriteStartAttribute(ReadOnlySpan<char>) write an attribute in no namespace. For a prefix or a namespace, use the string overloads.
  • Single-quoted attribute values and a choice of how to escape. The output form is fixed.

See also

Use Utf8XmlReader

Read UTF-8 XML with the reader that pairs with this writer.

Use XmlNode

Build and edit a document as a tree, then write it.

Custom converters

Use the writer and the reader inside a converter for your own type.

Migrate from XmlReader and XmlWriter

Map System.Xml.XmlWriter code to Utf8XmlWriter.

Streaming

Write and read large documents with the serializer.

Benchmarks

See how the writer compares with System.Xml.XmlWriter.
API reference: Utf8XmlWriter, XmlWriterOptions, XmlEncodedText, XmlVersion, XmlException.