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.- Names are compared with
LocalNameEqualsandNamespaceUriEquals, against UTF-8 literals ("Item"u8). No string is created for a name. - A value is read with a typed method,
GetBooleanorTryGetDecimal, that parses the XSD lexical form. You don’t callXmlConvert. - The input is UTF-8 bytes in a span, not a
TextReader. See Read from a stream.
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
- Every depth is the one
XmlReader.Depthreports. The emptyItemelement and theNotestart tag are both children ofOrder, so both are at depth 1. - The white space after
<Order>and the comment are reported, asXmlReaderreports them by default. White space is aTexttoken; there is no separateWhitespacetoken type. Itemhas one token. CheckIsEmptyElementbefore you wait for an end tag.GetStringreturnsFragile & heavy, with the entity reference resolved.
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
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
Disposemethod. 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 aStream. 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
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
Write a document
The following pair writes the same inventory document to a stream.- You construct the writer. There’s no
Createfactory. WriteStartDocumentandWriteEndDocumentare gone. The XML declaration is written before the first content unlessOmitXmlDeclarationistrue.WriteValuebecomesWriteNumberValue,WriteBooleanValue, orWriteStringValue, as inUtf8JsonWriter.- No encoding is set, and no byte order mark is written. The
System.Xmlcode has to ask for UTF-8 without one.
Writer members
Where aUtf8XmlWriter 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
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
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.