Definition
Assembly: CloudNimble.XmlEssentials.dll Namespace: CloudNimble.Text.XmlSyntax
Summary
Provides a mechanism for examining the structural content of an XML document without automatically instantiating data values. This class cannot be inherited.Usage
XmlDocument parses a whole XML document and gives you read-only, random access to it through XmlElement. It’s the XML counterpart of JsonDocument: the document rents its buffers from the shared array pool, so create it in a using statement.
Parse has an overload for a string, a ReadOnlySpan<char>, UTF-8 bytes in a ReadOnlySpan<byte> or a ReadOnlySequence<byte>, and a Stream of UTF-8. Start every query at RootElement.
ParseAsync, which reads aStreamwithout blocking and then parses it.TryParse, which returnsfalsewhereParsethrows anXmlException.ParseValue, which builds a document from the element aUtf8XmlReaderis positioned on, andTryParseValue, which returnsfalseand leaves the reader where it was when the element isn’t all in a block that isn’t the last one, or when the reader is on an end tag.DiscoverNamespaces, which returns the prefixes and namespaces a document declares without building a document. See Take them from an existing document.
Declaration is the XML declaration that was parsed, or null. WriteTo writes the document to a Utf8XmlWriter.
A document keeps comments and the white space between elements by default, so that parsing a document and writing it back doesn’t lose its comments or its indentation. Both appear among the children of an element, so check ValueKind when you enumerate. To leave them out, pass an XmlDocumentOptions with CommentHandling = XmlCommentHandling.Skip and WhitespaceHandling = XmlWhitespaceHandling.Insignificant.
For a walkthrough of every member, see How to read XML with XmlDocument and XmlElement.
Remarks
This class is the XML counterpart ofJsonDocument in System.Text.Json. The document is read-only.
It uses buffers from the shared array pool, and XmlDocument.Dispose returns them. A document that
is not disposed does not return its buffers to the pool. Using the document or an
XmlElement that was obtained from it after it is disposed throws
ObjectDisposedException.
Comments and processing instructions before and after the document element are kept for
XmlDocument.WriteTo. They are not children of XmlDocument.RootElement. Comments are kept by default, so that
a document that is parsed and written back does not lose them. To leave them out, set
XmlDocumentOptions.CommentHandling to XmlCommentHandling.Skip.
The document owns a pooled copy of the UTF-8 input. Names and values that contain no entity or
character references are stored as offsets into that copy. Only values that had references
expanded and namespace URIs are copied a second time.
Examples
Parse a document and write it back
WriteTo writes what was parsed, comments included. This document is already spelled the way the writer spells XML, so it comes back identical.
See what a round trip normalizes
A round trip preserves the content, the comments, and the indentation inside the root element. It isn’t byte for byte when the input spells something differently from the writer.Order are kept. The white space outside the root element is dropped, the declaration and the attribute quotes are written the writer’s way, and A is written as A. The white space inside a tag isn’t kept: the attributes follow XmlWriterOptions.AttributeStyle, and the empty-element tag follows EmptyElementStyle, so with the defaults <Notes /> becomes <Notes/>. The line ends follow NewLine, which the sample sets to "\n", so the CRLF of the input becomes LF.
View the complete sample on GitHub
Parse one element at a time from a reader
ParseValue reads the element a Utf8XmlReader is on and leaves the reader on its end tag, so only one record is in memory at a time.
Test input without an exception
Read the XML declaration
Best Practices
- Dispose every document. Use a
usingstatement. A document that isn’t disposed never returns its buffers to the array pool. That includes a document returned byTryParse,ParseValue, andXmlSerializer.SerializeToDocument. - Copy values out before the document is disposed. An
XmlElementis usable only while its document is alive. Return strings, numbers, or aCloneNodecopy from a method, not anXmlElement. - Pass UTF-8 when you have UTF-8. The
stringandReadOnlySpan<char>overloads convert the text to UTF-8 before they parse it. - Set
MaxDocumentByteCountfor input from outside your process. It’s the only limit that is off by default, and a document holds its whole input in memory. - Expect comments and white space when you enumerate. Both are kept by default so that a round trip doesn’t lose comments or indentation. Check
ValueKindin every loop overEnumerateChildren. - Turn them off when you only read values. Parse with
CommentHandling = XmlCommentHandling.SkipandWhitespaceHandling = XmlWhitespaceHandling.Insignificant, and the children of an element are only what carries data. - Read values from leaf elements. The text of an element that has child elements includes the white space between them.
- Don’t rely on identical bytes after a round trip. Content, comments, and indentation inside the root are preserved. Quote style, the declaration, and white space outside the root are written the writer’s way. Line ends, the layout of attributes, and the form of an empty-element tag follow the
NewLine,AttributeStyle, andEmptyElementStyleproperties ofXmlWriterOptions. - Use
TryGetChildandTryGetAttributefor optional names.GetChildandGetAttributethrow anXmlExceptionwhen the name is missing. - Don’t parse into a document only to deserialize it.
XmlSerializer.Deserializereads text, bytes, and streams directly. Deserialize from a document or an element when you need to inspect the XML first.
Patterns
Read, then copy out
Parse in ausing statement, read what you need through RootElement, and let the document go. Only the values you copied (strings, numbers, a cloned node) leave the block.
Stream with a reader, query with a document
Read a large input forward withUtf8XmlReader and call ParseValue on each record. Each record gets random access, and only one is in memory. The examples section shows the loop.
Inspect, then deserialize
Parse the document, check what it is (a root name, a version attribute), and pass the document or one of its elements toXmlSerializer.Deserialize.
Read here, edit there
The document can’t be changed. CallXmlElement.CloneNode on the element you need to edit, change the copy in the mutable tree, and write the copy. CloneNode copies everything under the element at once, so the copy stays valid after the document is disposed. When you parse only to edit, XmlNode.Parse gives you the tree directly. See How to build and change XML with XmlNode.
Copy part of a document into new output
Open aUtf8XmlWriter, write your own elements, and call XmlElement.WriteTo for the parts you take from the document. The writer declares any namespace the copied element needs.
Considerations
Lifetime and memory
- The document owns a pooled copy of the UTF-8 input and a pooled table with one row per node. Names and values are offsets into that copy. Only values that had entity or character references expanded, and namespace URIs, are stored a second time.
Disposeclears the buffers and returns them toArrayPool<T>.Shared. After that, the document and everyXmlElementfrom it throwObjectDisposedException.- Parsing allocates the
XmlDocumentobject and, in the usual case, nothing else. In the project’s benchmarks, parsing four real documents is 3.1× to 3.4× faster thanSystem.Xml.XmlDocumentand allocates about 104 bytes, whereSystem.Xml.XmlDocumentallocates 127 KB to 709 KB. See Benchmarks. - The whole document is in memory. For input that is too large for that, read it with
Utf8XmlReaderand useParseValuefor the parts that need random access. ParseAsyncreads the stream asynchronously and then parses it in one pass.
What is kept
The defaults aim at no surprises on a round trip, for example when a file is edited and saved back to source control.- Comments are kept by default (
XmlCommentHandling.Allow). SetXmlDocumentOptions.CommentHandlingtoSkipto leave them out of the document, or toDisallowto reject them. - White space that is the only text between two tags inside the root element, such as indentation, is kept by default (
XmlWhitespaceHandling.Significant). Each run is aTextnode among the children, and it’s part of the text of the element that contains it. SetXmlDocumentOptions.WhitespaceHandlingtoInsignificantto leave it out. - Comments and processing instructions before and after the root element are kept for
WriteTo. They aren’t reachable fromRootElement. - The declaration is kept as an
XmlDeclarationInfo. Its encoding is always reported asutf-8. - White space outside the root element isn’t kept: after the declaration, around comments in the prolog, and the final line break.
What is rejected
Parse throws an XmlException for input that isn’t well formed, has no root element or more than one, declares an encoding other than UTF-8, contains a document type declaration (<!DOCTYPE ...>), or exceeds a limit in the options.
Writing
WriteTokeeps comments, white space between elements, namespace declarations where they were, attribute order, and the difference between<e/>and<e></e>.- The result has the same content but isn’t always the same bytes. Attribute values are written with double quotes, and a character reference such as
Ais written as the character. White space inside a tag isn’t kept: the attributes are laid out asXmlWriterOptions.AttributeStylesays (one space before each, by default), and an empty-element tag has the formEmptyElementStylesays (<e/>by default, so<e />is written<e/>). Every line end is written asNewLine, which defaults toEnvironment.NewLine. - A parsed declaration is written with the parsed version and
encoding="utf-8", even when the writer’sOmitXmlDeclarationistrue. When the document has no declaration, the writer decides: aUtf8XmlWriteradds one unlessXmlWriterOptions.OmitXmlDeclarationistrue. - Writing a parsed document doesn’t allocate.
Thread safety
A document doesn’t change after it’s parsed, so several threads can read it at the same time. Don’t dispose it while another thread is reading.Differences from other APIs
- Unlike
System.Xml.XmlDocumentandXDocument, this type is read-only, and its nodes areXmlElementcursors into the document’s buffers rather than objects. You query it with theXmlElementlookups and enumerators. For a tree you can change, seeCloudNimble.Text.Xml.Nodes.XmlNode, and for the full comparison, Migrate from XDocument and System.Xml.XmlDocument. - Unlike
JsonDocument, the root can be preceded by a declaration, comments, and processing instructions, which the document keeps for writing.
Constructors
.ctor Inherited
Inherited from
objectSyntax
Properties
Declaration
Gets the XML declaration of this document.Syntax
Property Value
Type:CloudNimble.Text.Xml.XmlDeclarationInfo?
The XML declaration that was read when the document was parsed, or null if the
document has no XML declaration. The version is reported as 1.0 or 1.1, and the
encoding is always reported as utf-8.
Exceptions
RootElement
Gets the root element of this XML document.Syntax
Property Value
Type:CloudNimble.Text.Xml.XmlElement
An XmlElement that represents the document element.
Exceptions
Methods
DiscoverNamespaces
Reads UTF-8 encoded XML and returns the namespaces it declares, each with the prefix it is declared under.Syntax
Parameters
Returns
Type:System.Collections.Generic.OrderedDictionary<string, string>
The namespace URIs, keyed by prefix, in the order the document first declares each prefix. The default
namespace of the document element has an empty string as its prefix.
Exceptions
Examples
Remarks
Every start tag in the document is examined for prefixes, not only that of the document element. A prefix that the document binds more than once is listed with the namespace of its first declaration. Thexml prefix is listed only if the document declares it.
A default namespace (xmlns="...") is listed only when the document element declares it. One
that an element further in declares names the elements under that element alone, so it could not be
declared for the whole document without renaming the rest.
The result can be assigned to XmlSerializerOptions.Namespaces, so that what is serialized
uses the prefixes of an existing document. No XmlDocument is built.
DiscoverNamespaces
Reads XML from a stream of UTF-8 bytes and returns the namespaces it declares, each with the prefix it is declared under.Syntax
Parameters
Returns
Type:System.Collections.Generic.OrderedDictionary<string, string>
The namespace URIs, keyed by prefix, in the order the document first declares each prefix. The default
namespace of the document element has an empty string as its prefix.
Exceptions
Remarks
See XmlDocument.DiscoverNamespaces for what is listed.DiscoverNamespaces
Reads XML text and returns the namespaces it declares, each with the prefix it is declared under.Syntax
Parameters
Returns
Type:System.Collections.Generic.OrderedDictionary<string, string>
The namespace URIs, keyed by prefix, in the order the document first declares each prefix. The default
namespace of the document element has an empty string as its prefix.
Exceptions
Remarks
See XmlDocument.DiscoverNamespaces for what is listed. The encoding that an XML declaration names is not checked, because the text is already decoded.Dispose
Syntax
Equals Inherited Virtual
Inherited from
objectSyntax
Parameters
Returns
Type:bool
Equals Inherited
Inherited from
objectSyntax
Parameters
Returns
Type:bool
GetHashCode Inherited Virtual
Inherited from
objectSyntax
Returns
Type:int
GetType Inherited
Inherited from
objectSyntax
Returns
Type:System.Type
MemberwiseClone Inherited
Inherited from
objectSyntax
Returns
Type:object
Parse
Parses a string that holds a single XML document into an XmlDocument.Syntax
Parameters
Returns
Type:CloudNimble.Text.Xml.XmlDocument
An XmlDocument representation of the XML document.
Exceptions
Remarks
The text is converted to UTF-8 in a pooled buffer that the document owns. XmlDocumentOptions.MaxDocumentByteCount applies to the UTF-8 size.Parse
Parses a span of characters that holds a single XML document into an XmlDocument.Syntax
Parameters
Returns
Type:CloudNimble.Text.Xml.XmlDocument
An XmlDocument representation of the XML document.
Exceptions
Remarks
The text is converted to UTF-8 in a pooled buffer that the document owns. XmlDocumentOptions.MaxDocumentByteCount applies to the UTF-8 size.Parse
Parses a span of UTF-8 bytes that holds a single XML document into an XmlDocument.Syntax
Parameters
Returns
Type:CloudNimble.Text.Xml.XmlDocument
An XmlDocument representation of the XML document.
Exceptions
Remarks
The bytes are copied into a pooled buffer that the document owns, so the document does not depend on xml after this method returns.Parse
Parses a sequence of UTF-8 bytes that holds a single XML document into an XmlDocument.Syntax
Parameters
Returns
Type:CloudNimble.Text.Xml.XmlDocument
An XmlDocument representation of the XML document.
Exceptions
Remarks
The bytes are copied into one pooled buffer that the document owns, so the document does not depend on xml after this method returns.Parse
Parses a stream of UTF-8 bytes that holds a single XML document into an XmlDocument. The stream is read to completion.Syntax
Parameters
Returns
Type:CloudNimble.Text.Xml.XmlDocument
An XmlDocument representation of the XML document.
Exceptions
Remarks
When XmlDocumentOptions.MaxDocumentByteCount is set, reading stops as soon as the stream is found to be longer than that limit. The stream is not closed.ParseAsync
Parses a stream of UTF-8 bytes that holds a single XML document into an XmlDocument, without blocking the calling thread. The stream is read to completion.Syntax
Parameters
Returns
Type:System.Threading.Tasks.Task<CloudNimble.Text.Xml.XmlDocument>
A task that produces an XmlDocument representation of the XML document.
Exceptions
Examples
Remarks
Anull stream is refused before the task is created. When
XmlDocumentOptions.MaxDocumentByteCount is set, reading stops as soon as the stream
is found to be longer than that limit. The stream is not closed.
ParseValue
Parses one XML element (including its attributes and descendants) from the provided reader.Syntax
Parameters
Returns
Type:CloudNimble.Text.Xml.XmlDocument
An XmlDocument representation of the element (and nested nodes) read from the reader.
Exceptions
Remarks
If the reader is positioned on an attribute, it is moved back to the element that owns the attribute. When this method returns, the reader is positioned on the end tag of the element, or on the element itself if it is an empty-element tag. The document copies the names and values it keeps, so it does not depend on the reader’s input after this method returns. The reader is not restored to its original position when this method throws.ReferenceEquals Inherited
Inherited from
objectSyntax
Parameters
Returns
Type:bool
ToString Inherited Virtual
Inherited from
objectSyntax
Returns
Type:string?
TryParse
Attempts to parse a span of UTF-8 bytes that holds a single XML document into an XmlDocument.Syntax
Parameters
Returns
Type:bool
true if xml is a well-formed XML document that is within
the limits set in options; otherwise, false.
Remarks
This method returnsfalse in every case where
XmlDocument.Parse throws an XmlException.
TryParseValue
Attempts to parse one XML element (including its attributes and descendants) from the provided reader.Syntax
Parameters
Returns
Type:bool
true if the element was read; false if the reader’s input ends
before the element does and Utf8XmlReader.IsFinalBlock is false,
or if the reader is on an end tag.
Exceptions
Examples
Remarks
This is the counterpart ofJsonDocument.TryParseValue. When this method returns
true, the reader is where XmlDocument.ParseValue leaves it: on the end tag of
the element, or on the element itself if it is an empty-element tag. When it returns
false or throws, the reader is where it was before the call, so the caller can
supply more input and call again. The element is read twice: once to find its end, and once to keep it.
WriteTo
Writes the document to the provided writer as XML.Syntax
Parameters
Exceptions
Remarks
The XML declaration (when the document has one) is written first, then the comments and processing instructions before the root element, the root element, and the comments and processing instructions after it. The declaration belongs to the document, so it is written whatever the writer’s XmlWriterOptions.OmitXmlDeclaration says: that option only decides whether the writer adds a declaration to a document that has none. Write with it set totrue to get back what was parsed. The
declaration is written with the version of the parsed document and
encoding="utf-8".
Related APIs
- CloudNimble.Text.Xml.XmlElement
- CloudNimble.Text.Xml.XmlDocumentOptions
- CloudNimble.Text.Xml.XmlDeclarationInfo
- CloudNimble.Text.Xml.XmlValueKind
- CloudNimble.Text.Xml.Utf8XmlReader
- CloudNimble.Text.Xml.Utf8XmlWriter
- CloudNimble.Text.Xml.XmlSerializer
- CloudNimble.Text.Xml.XmlException
- CloudNimble.Text.Xml.Nodes.XmlNode