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 anIBufferWriter<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 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. WriteEndElementtakes no name. The writer knows which element is open. An element with no content, likeNotes, 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.WrittenSpanorbuffer.WrittenMemorywhere the XML is going.
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 aStream 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.
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 withWriteStartAttribute. 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 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=.
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, aWriteElement* method writes the start tag, the value, and the end tag together.
To choose between the two ways of closing an element:
WriteEndElementwrites</Notes>when the element has content. When it has none, the element is written in the formEmptyElementStyleasks for, which is<Notes/>by default.WriteFullEndElementalways writes the end tag, so an element with no content becomes<Notes></Notes>, whateverEmptyElementStyleis. 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
EveryWriteElement* 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.
- A
u8literal or anXmlEncodedTextis already UTF-8, so the writer copies the name without converting it. - A
nullliteral for the text doesn’t say which overload you mean, and the call doesn’t compile. Cast it, as(string?)nullin the sample, or pass astringvariable.Utf8JsonWriter.WriteStringhas 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.
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
NewLineoption says. The sample setsNewLineto"\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.
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 writexmlns attributes yourself unless you want to choose where they go. The writer tracks which namespaces are in scope and declares what’s missing.
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="">.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 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. SetIndented 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:
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.
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.
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
WithAttributeStyle = 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.
- A namespace declaration and
xsi:nilare attributes and are counted. PerLineworks with or withoutIndented.AttributesPerLinecan’t be negative. A negative value throwsArgumentOutOfRangeException.
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 property accepts
"\n"and"\r\n", the two valuesJsonWriterOptions.NewLineaccepts in System.Text.Json. Any other string throwsArgumentOutOfRangeException, andnullthrowsArgumentNullException. The default isEnvironment.NewLine. - No value changes. A reader gives a carriage return followed by a line feed back as one line feed, so the text of
ris read back as"a\nb". - A carriage return that is part of a value is still written as

, and a line feed in an attribute value is still written as
. 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.
What to notice:
- Comments and processing instructions are indented like elements. With
Indentedset, 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
Addressstays 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.
Write XML 1.1
XML 1.0 has no way to write most control characters. If your data can contain them, setVersion 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.
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 astring, 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.
Encodetakes astring, aReadOnlySpan<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
XmlEncodedTextname is the same element as one written with the name as astring. XmlEncodedTextis for element names with no prefix and no namespace argument:WriteStartElement,WriteEmptyElement,WriteNilElementand everyWriteElement*method have an overload for it. LikeWriteStartElement("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 au8literal (as"Items"u8in 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:BytesPendingis the number of bytes written but not yet committed.BytesCommittedis 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.
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, useFlushAsync 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.
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.
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
BytesCommittedand the depth to 0 and forgets the namespaces in scope. The next document gets its own XML declaration, unlessOmitXmlDeclarationis 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.
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.
Validation
The writer checks what you write and throws anXmlException 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:
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 ausing statement, Dispose then runs, throws its own exception about the unclosed elements, and that exception replaces the first one.
Skip validation
When you’re certain that your code writes correct XML,SkipValidation turns most checks off.
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 anXmlException whose message names the option.
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.
WriteRawValuecan write them, unchecked, butUtf8XmlReaderdoesn’t read a document that has a DTD. - Asynchronous
Write*methods. Writing fills a buffer, and onlyFlushAsyncandDisposeAsyncdo I/O. - Closing elements for you. There’s no method that ends every open element, and
Disposedoesn’t. - Namespaced attributes from span names.
WriteAttributeString(ReadOnlySpan<byte>, ReadOnlySpan<byte>),WriteAttributeString(ReadOnlySpan<char>, ReadOnlySpan<char>), andWriteStartAttribute(ReadOnlySpan<char>)write an attribute in no namespace. For a prefix or a namespace, use thestringoverloads. - 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.Utf8XmlWriter, XmlWriterOptions, XmlEncodedText, XmlVersion, XmlException.