Utf8XmlReader is a forward-only reader for UTF-8 encoded XML. It reads one token at a time from a span or a sequence of bytes and gives you each name and value as a slice of your own input. This article shows how to use it, from the basic loop to reading a stream in blocks and reading without allocating.
Use the reader when you need the lowest overhead, when a document is too large to hold as a tree, or when you write a custom converter. To map XML to your own types, use XmlSerializer. To query a document at random, use XmlDocument.
If you know Utf8JsonReader from System.Text.Json, you already know the shape of this API: a ref struct with a Read method, a TokenType property, ValueSpan, Get* and TryGet* methods, and a state value for reading in blocks.
What a ref struct reader means for your code
Utf8XmlReader is a ref struct because it holds a span over your input. The compiler enforces the rules that follow from that:
- You can’t store a reader in a field of a class, in an array, or in a collection.
- You can’t use a reader across an
awaitor ayield return, and a lambda can’t capture one. - To let another method advance your reader, pass it with
ref. Passing it by value copies it, and the caller’s reader doesn’t move.
- The input is UTF-8 bytes. Pass a
u8literal, abyte[], aReadOnlySpan<byte>, or aReadOnlySequence<byte>. To read astring, encode it withEncoding.UTF8.GetBytesfirst, or useXmlDocument.Parse(string). - A copy isn’t fully independent.
var lookahead = reader;compiles, and you can use the copy to look ahead inside the element the original is on. The copy shares the original’s working memory, so don’t advance two copies in turn, and don’t go back to the original after the copy has read past the end of that element.
A reader isn’t thread safe, and it can’t be shared between threads anyway because it’s a
ref struct. For the rules that apply to the other types, see Thread safety.Read tokens in a loop
Create a reader over the bytes and callRead until it returns false. After each successful call, TokenType says what the reader is on.
- The sample sets two options so that the loop sees data only. By default, the reader also reports comments and the white space between elements, such as the indentation of this document, so that nothing in a document is lost when you read it and write it back. These two options are the ones to set in a loop that only wants data. See Comments, white space, CDATA, and processing instructions.
CurrentDepthis the number of elements the token is inside. The root element is at depth 0. A start tag and its end tag are at the same depth, and the content between them is one deeper.<Gift/>produces one token, at the depth a<Gift>start tag would have. See Handle empty elements.- Attributes aren’t tokens in the loop. You visit them from the start tag, as the next section shows.
Find elements and read attributes
LocalNameEquals compares the name of the current element or attribute with a name you pass, without creating a string. Pass a u8 literal to compare bytes with bytes. There are also overloads that take a string or a ReadOnlySpan<char>.
On a start tag, MoveToNextAttribute moves to the first attribute, then to each one after it, and returns false when there are no more. While the reader is on an attribute, TokenType is Attribute, and the name and value members describe the attribute. MoveToElement puts the reader back on the start tag.
MoveToElement before the next Read. Read always continues after the start tag. Call it when you want the element’s own name again, or when you want to walk the attributes a second time.
AttributeCount and the attribute walk include namespace declarations (xmlns and xmlns:prefix). See Read namespaces.
Handle empty elements
An empty element such as<Gift/> is one StartElement token with IsEmptyElement set to true. The reader doesn’t make up an EndElement token for it. An element written as <Note></Note> is two tokens.
This matters whenever your code counts depth or waits for an end tag: check IsEmptyElement on every start tag.
This is the same rule as
System.Xml.XmlReader.IsEmptyElement, and it’s different from JSON, where every start token has an end token.Read text and typed values
The value of aText, CData, or Attribute token is available in three ways:
GetStringreturns the value as a newstring. It allocates.Get*methods such asGetInt32parse the UTF-8 bytes in place and return a .NET value. They throw anXmlExceptionwhen the value isn’t valid for the type.TryGet*methods do the same and returnfalseinstead of throwing.
reader.Read() after a start tag to move to the text inside it. That’s safe when you know the element has text. For an element that can be empty (<Total/> or <Total></Total>), check that the token after the start tag is Text or CData before you read a value. The sample uses the default options, so the reader also reports the indentation between the elements as Text tokens. The loop passes over them because it acts only on start tags.
The typed methods read the lexical forms of XML Schema, not the formats of the current culture:
GetString never returns null: an empty value is an empty string.
GetNil is the one method you call on a start tag. It returns true when the element has an xsi:nil attribute, in the XML Schema instance namespace, with the value true or 1. For how the serializer uses it, see Null values and xsi:nil.
Work with the value as bytes
ValueSpan is the value as UTF-8 bytes. When the value has no character or entity reference and no line end to normalize, the span is a slice of your input and reading it costs nothing. When the value has one, the reader decodes it into its own buffer and ValueIsEscaped is true. Either way, ValueSpan is the decoded value.
Three members let you use the value without creating a string:
ValueTextEqualscompares the value with bytes, characters, or a string.CopyStringcopies the value into a buffer of bytes or characters that you own and returns the length.ValueSpanitself can go to any API that takes UTF-8, such asUtf8Parseror another writer.
Read namespaces
The reader resolves namespaces for you. On a start tag, an end tag, or an attribute:LocalNameSpanis the name without its prefix.PrefixSpanis the prefix, or an empty span.NamespaceUriSpanis the namespace the name belongs to, or an empty span when it has none.NamespaceUriEqualscompares the namespace with one you pass, asLocalNameEqualsdoes for the local name.
- An element without a prefix is in the default namespace.
titleis in the Atom namespace becausefeeddeclaresxmlns="...". - An attribute without a prefix is in no namespace.
langhas an empty namespace even though a default namespace is in scope. This is a rule of Namespaces in XML, and code that maps attributes gets it wrong more often than anything else. - Declarations on a start tag apply to that start tag.
feedis resolved with the default namespace that it declares itself. - Namespace declarations are attributes. They show up in the attribute walk in the reserved namespace
http://www.w3.org/2000/xmlns/(the constantXmlNamespaces.Xmlns). Skip them when you only want the element’s data.
Undeclared namespace prefix.), and so are two attributes on one element with the same local name and namespace (Duplicate attribute.). For namespaces in the serializer, see Namespaces.
Comments, white space, CDATA, and processing instructions
By default the reader reports everything in a document: comments asComment tokens, and text that is only white space between elements as Text tokens. The XML specification asks a processor to pass all of a document’s characters to the application, and System.Xml.XmlReader has the same default. It means that XML you read and write back keeps its comments and its layout.
Code that only wants the data sets two properties of XmlReaderOptions. The sample reads one document with the defaults and then with both left out.
PrintTokens is the loop that reads each kind of token:
- Processing instructions are always reported. The target is in
LocalNameSpanand the data is inValueSpan. - A CDATA section is its own token type. Its value is the text between the delimiters, with nothing decoded. Treat
TextandCDatathe same way unless you need to know which one the document used. - A comment is read with
GetComment, which returns the text between the delimiters. - White space outside the root element is never reported, whatever the options say.
XmlReaderOptions.CommentHandling takes one of these values:
XmlReaderOptions.WhitespaceHandling takes one of these values:
White space inside a value is always kept.
<Name> Ada </Name> has the value " Ada " under every setting. Line ends in a value are always read as a line feed, as XML requires.
Insignificant and None treat white-space-only text as indentation only when it carries no content. The reader still reports it as a Text token, under every setting, when:
- It’s the whole content of the element.
<Code> </Code>has the value" ". - The element already has text before it. In
<p>Hello <b>you</b> <i>there</i></p>, the space between</b>and<i>is part of the sentence, and so is reported. A CDATA section counts as text. xml:space="preserve"is in force. It applies to the element that has it and to everything inside, until an element setsxml:space="default".
new XmlReaderOptions(), default(XmlReaderOptions), a reader created without options, and new XmlReaderState() all mean the same thing: comments and white space are reported. The serializer is different. XmlSerializerOptions skips comments and treats white space between elements as insignificant by default, so a custom converter sees data only.The XML declaration and XML 1.0 or 1.1
When a document starts with an XML declaration, the reader reports it as anXmlDeclaration token and sets Version. A document with no declaration is XML 1.0. You don’t tell the reader which version to expect. It applies the rules of the version the document names.
The rules for the declaration itself:
- It must be the first thing in the document, after an optional byte order mark. White space, a comment, or anything else before it is an error.
- The version must have the form
1.x.1.1selects XML 1.1. Any other version number is read as XML 1.0, as the XML 1.0 specification asks. - The encoding, when it’s named, must be UTF-8. See What the reader doesn’t support.
- On the
XmlDeclarationtoken,ValueSpanholds the pseudo-attributes as they were written, such asversion="1.0" encoding="utf-8". To get the version, the encoding, andstandaloneas values, parse the document withXmlDocumentand readXmlDocument.Declaration, anXmlDeclarationInfo.
Skip elements
When you don’t need an element, callSkip on its start tag. The reader moves over the element’s attributes, its text, and all of its descendants, checking that they’re well formed as it goes, and stops on the element’s end tag. The next Read moves to whatever follows.
- On an empty element,
Skipdoes nothing, because the element is already complete. - Call
Skipon a start tag. On any other token it does nothing, because only a start tag has children. - When you read in blocks and the element isn’t all in the current block,
Skipthrows anXmlException(Cannot skip: more data is required.). UseTrySkipthere instead. It returnsfalseand puts the reader back on the start tag, with its attributes, asUtf8JsonReader.TrySkipdoes.
TrySkip returns false, BytesConsumed and CurrentState describe the point just after the start tag, so a reader you create from them with more data reads the element’s content one token at a time. To skip the element whole once more data has arrived, keep a copy of the reader from before the Read that reached the start tag, and continue from the copy instead:
reader reads ahead inside the element that before is in, and is then dropped.
Read a fragment
A document has exactly one root element. To read a fragment that has several top-level elements, or none, setAllowMultipleRoots.
Item throws Multiple root elements are not allowed., and an input with no element throws Document does not have a root element. Text outside an element is an error with or without the option.
Read from a ReadOnlySequence
AReadOnlySequence<byte> is what System.IO.Pipelines and many network APIs hand you: one logical buffer made of several blocks. Pass it to the reader as it is.
BufferSegment.cs
Keyboard is split between the two blocks, and the reader still returns it whole. Here’s what happens to your input:
- One block: the reader reads the sequence where it lies and copies nothing.
- More than one block: the reader copies the sequence into one array first, and then reads the array. That costs one allocation the size of the input. This is where
Utf8XmlReaderdiffers fromUtf8JsonReader, which reads across blocks in place.
Position gives the reader’s place as a SequencePosition, so you can tell a PipeReader how much was consumed. The sequence constructors also come in an isFinalBlock form, which works as the next section describes.
Read a stream in blocks
The reader works on memory, not on aStream. To read a stream without loading all of it, read a block into a buffer, give the block to a reader, and carry the reader’s state to the next block. Three members make that work:
- The
isFinalBlockconstructor argument tells the reader whether more data follows. When it’sfalseand the block ends in the middle of a token,Readreturnsfalseinstead of throwing. BytesConsumedis how many bytes of the block the reader finished with. The bytes after it are the start of a token that isn’t complete yet.CurrentStateis anXmlReaderState: everything the next reader needs to continue, including the open elements, the namespaces in scope, the XML version, and the line count.
Utf8JsonReader with JsonReaderState.
1
Create the first state from your options
Use
new XmlReaderState(options). The state carries the options to every reader that you create from it.2
Fill the buffer and create a reader over it
Read from the stream into the free part of the buffer. Pass
isFinalBlock: true only when the stream has ended.3
Read tokens until Read returns false
Keep what you know about your place in the document in your own variables, not in the flow of the code. A token and the one after it can arrive in different blocks.
4
Save the state and keep the unread bytes
Take
CurrentState, move the bytes after BytesConsumed to the front of the buffer, and grow the buffer if it’s full.- A token is never split. A start tag arrives with all of its attributes, and a text value arrives whole. That’s why the buffer must be able to grow to the size of the largest token: here the 16-byte buffer grew once, to hold the 17 bytes of the start tag
<Order id="1042">. - The last pass has no new bytes. When the stream returns 0, the loop runs once more with
isFinalBlock: true. That pass is what reports an incomplete document: withisFinalBlock: true, a document that ends early throwsUnexpected end of XML. BytesConsumedcounts from the start of the current block.TokenStartIndexand the positions on anXmlExceptioncount from the start of the document.- The reader lives inside one pass of the loop. Because it’s a
ref struct, it can’t cross anawait. In anasyncmethod, do theawait stream.ReadAsync(...)between passes and keep the reader in a synchronous helper method that takes the buffer and the state. CurrentStateallocates. It copies the names of the open elements and the namespace bindings so that the state doesn’t depend on a buffer you’re about to overwrite. Read it once per block, not once per token.- The state keeps the context of the open elements.
xml:space, and whether an element already has text, carry over to the next block, so white space is reported the same way as when the document is read in one piece.
Read without allocating
Reading tokens, comparing names withu8 literals, and parsing typed values don’t allocate. (GetString, GetComment, and GetBytesFromBase64 return new objects, so they do.) A reader needs memory of its own in only four cases:
- A value has a character or entity reference, or a line end other than a line feed, and has to be decoded.
- A start tag has more than eight attributes.
- More than eight namespace declarations are in scope.
- Elements are nested more than eight deep.
- Any size is correct. The reader takes what it can from the buffer and allocates only when the buffer runs out, so a buffer that’s too small costs an allocation and never an error. A larger buffer covers more documents.
- The contents on entry don’t matter. You don’t have to clear the buffer, and you can pass the same one to the reader for every block of a document, with the
(utf8Xml, scratch, isFinalBlock, state)constructor. - The buffer can come from anywhere:
stackalloc, a pooled array, or a field you reuse. - The reader may overwrite the buffer for as long as you use the reader. Don’t use it for anything else in the meantime. A copy of the reader uses the same buffer, under the rules for copies at the top of this article.
- The scratch constructors take a
ReadOnlySpan<byte>. To read aReadOnlySequence<byte>with one, passsequence.FirstSpanwhenIsSingleSegmentistrue.
System.Xml.XmlReader, and with a scratch buffer it allocates nothing. For the numbers, with and without a scratch buffer, see Benchmarks.
Set limits
The reader enforces limits so that a hostile document can’t make it use unbounded memory or stack. Each limit is a property ofXmlReaderOptions, and exceeding one throws an XmlException whose message names the property.
Drain reads the document to the end and returns the message of the exception, if there is one:
new XmlReaderOptions() is already protected.
MaxDocumentByteCount is the one limit where 0 means no limit. The reader checks it when you construct it, against the bytes read so far plus the length of the block you pass. When you read a stream in blocks, the state carries the count from block to block.
The text, comment, and processing instruction limits count the bytes as they are in the document, before references are expanded. When you read in blocks, a value, a comment, or a processing instruction that is already longer than its limit throws as soon as the reader sees it, without waiting for its end, so a sender can’t make you buffer a token that never ends.
For how to choose limits for input you don’t trust, see Security.
Handle errors
The reader throwsCloudNimble.Text.Xml.XmlException when the input isn’t well formed, when a limit is exceeded, and when a Get* method can’t parse a value. The exception says where the reader was.
What to know about errors:
- The position is where the reader stopped, which is at the problem or right after it. In the sample it’s the end of the bad end tag.
- An error ends the read. Don’t call
Readagain on a reader that threw. Start over with a corrected document. - This isn’t
System.Xml.XmlException. The two types are unrelated, so acatchfor one doesn’t catch the other. If a file imports bothSystem.XmlandCloudNimble.Text.Xml, name the type in full. - The reader checks as it goes. An error at the end of a large document is thrown after your code has handled everything before it. If you must not act on a document that’s malformed, read it to the end first, or parse it with
XmlDocument.
What the reader doesn’t support
Utf8XmlReader is a non-validating reader for UTF-8 documents without a document type declaration. It rejects what it doesn’t support with an exception. It never skips it silently.
- No DTDs. A
<!DOCTYPEdeclaration throws. There’s no option to allow one, so a document can’t define entities, and entity-expansion and external-entity attacks have nothing to work with. See Security. - Only the five predefined entities and character references.
&,<,>,",', and references such as©and—are decoded. Any other entity, including HTML ones such as , throws. - UTF-8 only. A declaration that names another encoding throws, and so do bytes that aren’t valid UTF-8. UTF-16 and UTF-32 input is recognized from its first bytes and throws
XmlEssentials is UTF-8 only. The input is UTF-16 or UTF-32.A UTF-8 byte order mark is accepted and skipped. To read a document in another encoding, transcode it to UTF-8 first, for example withEncoding.CreateTranscodingStream, and remove or rewrite the encoding in its declaration. - No validation. The reader checks that a document is well formed. It doesn’t validate against a DTD or an XML Schema.
- No
StreamorTextReaderconstructor, and no asynchronousRead. Use the block loop in this article, or letXmlSerializerorXmlDocumentread the stream. - Forward only. There’s no way to go back. Copy the reader to look ahead, within the limits given at the top of this article.
See also
Use Utf8XmlWriter
Write UTF-8 XML with the writer that pairs with this reader.
Use XmlDocument
Parse a whole document and query it at random.
Custom converters
Use the reader and the writer inside a converter for your own type.
Migrate from XmlReader and XmlWriter
Map
System.Xml.XmlReader code to Utf8XmlReader.XML conformance
See what the reader accepts and rejects, and why.
Security
Choose limits for input you don’t trust.
Utf8XmlReader, XmlReaderOptions, XmlReaderState, XmlTokenType, XmlCommentHandling, XmlWhitespaceHandling, XmlVersion, XmlException.