Skip to main content
This article is for developers who read XML with System.Xml.XmlReader or write it with System.Xml.XmlWriter and want to move that code to Utf8XmlReader and Utf8XmlWriter. It maps each member you use to its counterpart, and then covers the differences that a rename doesn’t fix. Utf8XmlReader and Utf8XmlWriter are the XML counterparts of Utf8JsonReader and Utf8JsonWriter in System.Text.Json. If you’ve used those, you already know the model: a ref struct reader over UTF-8 bytes, and a writer over an IBufferWriter<byte> or a Stream. In the project’s benchmarks, Utf8XmlReader reads four real documents 1.5× to 2.3× faster than XmlReader, and a reused Utf8XmlWriter writes a 200-item catalog 2.0× faster than XmlWriter while allocating nothing.

Table of differences

Read a document

The following pair reads the same inventory document: a namespace, two attributes on each item, typed values, and a subtree that the code skips.
The XmlEssentials code produces the following output:
The loop has the same shape in both. Three things are different:
  • Names are compared with LocalNameEquals and NamespaceUriEquals, against UTF-8 literals ("Item"u8). No string is created for a name.
  • A value is read with a typed method, GetBoolean or TryGetDecimal, that parses the XSD lexical form. You don’t call XmlConvert.
  • The input is UTF-8 bytes in a span, not a TextReader. See Read from a stream.
View the complete sample on GitHub

Reader members

Depth

CurrentDepth counts the elements the token is inside, as XmlReader.Depth does. The root element is at depth 0, and a start tag, its end tag, and an empty element in the same place are at the same depth. The following code prints every token of a small document:
Program.cs
The code produces the following output:
What to notice:
  • Every depth is the one XmlReader.Depth reports. The empty Item element and the Note start tag are both children of Order, so both are at depth 1.
  • The white space after <Order> and the comment are reported, as XmlReader reports them by default. White space is a Text token; there is no separate Whitespace token type.
  • Item has one token. Check IsEmptyElement before you wait for an end tag.
  • GetString returns Fragile & heavy, with the entity reference resolved.
View the complete sample on GitHub

Reader settings

XmlReaderSettings is a class that you pass to XmlReader.Create. XmlReaderOptions is a struct that you pass to the constructor. The defaults for comments and white space are the same in both: the reader reports them. new XmlReaderOptions(), default(XmlReaderOptions), and the constructor that takes only the XML all behave the same way. The following code is the counterpart of IgnoreComments = true and IgnoreWhitespace = true:
Program.cs
The code produces the following output:
The comment and the space after it are gone. With the default options, the reader reports both, between the two StartElement tokens. View the complete sample on GitHub

The reader is a ref struct

XmlReader is a class: you can store it in a field, pass it to an async method, and keep it alive as long as its stream. Utf8XmlReader is a ref struct, as Utf8JsonReader is. That has consequences for how you structure code:
  • Pass it by reference (ref Utf8XmlReader reader). Passing it by value copies the reader, and the caller’s copy doesn’t advance.
  • It can’t be a field of a class, can’t be boxed, and can’t be used across an await. Read synchronously from a buffer, and do the asynchronous I/O between buffers.
  • It has no Dispose method. It owns nothing that needs to be released.
  • It doesn’t own or read a stream. See the next section.

Read from a stream

No constructor takes a Stream. You have three choices, from the least code to the most control. Let a higher-level API read the stream. XmlSerializer.Deserialize, XmlSerializer.DeserializeAsync, and XmlDocument.Parse all take a Stream and use Utf8XmlReader inside. If your XmlReader code fills in objects or walks a whole document, this replaces all of it. See Deserialize and Use XmlDocument. Read the stream into a buffer, then read the buffer. This is the direct replacement when the document fits in memory:
Program.cs
The code produces the following output:
View the complete sample on GitHub Read the stream in pieces. For a document that is too large to buffer, read a block, create a reader over it with isFinalBlock: false, read tokens until Read returns false, save CurrentState, and continue with the next block. This is the pattern Utf8JsonReader uses with JsonReaderState. Use Utf8XmlReader and Streaming show the complete loop.

DTDs are rejected

XmlReader can prohibit, ignore, or parse a document type declaration. Utf8XmlReader has no setting: a <!DOCTYPE is an error, and so is a reference to an entity other than the five predefined ones. This closes XML external entity (XXE) and entity expansion attacks without any configuration.
Program.cs
The code produces the following output:
If your documents depend on a DTD for entities or default attribute values, XmlEssentials can’t read them. See Security and XML conformance. View the complete sample on GitHub

Write a document

The following pair writes the same inventory document to a stream.
Both produce the following output:
What changed:
  • You construct the writer. There’s no Create factory.
  • WriteStartDocument and WriteEndDocument are gone. The XML declaration is written before the first content unless OmitXmlDeclaration is true.
  • WriteValue becomes WriteNumberValue, WriteBooleanValue, or WriteStringValue, as in Utf8JsonWriter.
  • No encoding is set, and no byte order mark is written. The System.Xml code has to ask for UTF-8 without one.
View the complete sample on GitHub

Writer members

Where a Utf8XmlWriter method takes a name or text as a string, it usually has overloads for ReadOnlySpan<char> and for UTF-8 in a ReadOnlySpan<byte> too. For xsi:nil, WriteNilElement(localName) writes an empty element with the attribute, and WriteNilValue() adds it to the element you’ve started. See Use Utf8XmlWriter.

Writer settings

new XmlWriterOptions() and default(XmlWriterOptions) write the same XML. The default line ending is Environment.NewLine, so set NewLine when the output must be the same on every operating system.
To write a fragment with no declaration into a buffer:
Program.cs
The code produces the following output:
The writer holds output in its own buffer until you call Flush or dispose it. Read the destination after that, as this sample does. View the complete sample on GitHub

Close every element

XmlWriter closes the elements that are still open when you call WriteEndDocument, Close, or Dispose. Utf8XmlWriter doesn’t: an open element at Dispose is an error, so a missing WriteEndElement can’t produce a document that looks complete.
Program.cs
The code produces the following output:
Code that relied on the old behavior, for example a using block that ends inside a loop, needs a WriteEndElement call for each WriteStartElement. View the complete sample on GitHub

What isn’t supported

See also

Use Utf8XmlReader

The complete guide to the reader, including reading in pieces.

Use Utf8XmlWriter

The complete guide to the writer.

Streaming

Large documents, pipes, and asynchronous sequences.

Security

Limits and defaults for untrusted input.

Namespaces

How prefixes and URIs are read and written.

Migrate from XDocument and XmlDocument

Move DOM code.
API reference: