Skip to main content
XmlDocument parses a whole XML document once and lets you read any part of it, in any order, without defining types for it. It’s read-only, and it keeps its data in buffers that it rents from the shared array pool, so you dispose it when you’re done. Each node you read from it is an XmlElement, a small struct that points into the document. XmlDocument and XmlElement are the XML counterparts of JsonDocument and JsonElement in System.Text.Json. If you know those types, the lifetime rules and most of the member names carry over.
These types are in the CloudNimble.Text.Xml namespace. They share their names with System.Xml.XmlDocument and System.Xml.XmlElement, so a file that imports both namespaces needs an alias or a fully qualified name.

Choose an API

XmlEssentials has four ways to read XML. Use the one that matches what you do with the data. You can combine them. A reader can hand one element to XmlDocument.ParseValue, a document can copy one element into the mutable tree with CloneNode, and the serializer can read from a document, an element, or a node. This page shows each of those.

Parse a document

XmlDocument.Parse has an overload for each kind of input: a string, a ReadOnlySpan<char>, a ReadOnlySpan<byte> of UTF-8, a ReadOnlySequence<byte> of UTF-8, and a Stream of UTF-8. Every overload copies the input into a buffer that the document owns, so the document doesn’t depend on your string, array, or stream after Parse returns.
The code produces the following output:
What to notice:
  • RootElement is the document element. It’s where every query starts.
  • When you already have UTF-8 bytes, pass them as bytes. The string and ReadOnlySpan<char> overloads convert the text to UTF-8 first.
  • The Stream overload reads the stream to its end and doesn’t close it. To read the stream without blocking, use ParseAsync.
  • The input must be UTF-8 (or text that the string overloads convert). In bytes, a declaration that names another encoding, such as encoding="utf-16", is rejected. In a string or a span of characters, the declared encoding isn’t checked.
  • Input that isn’t a well-formed XML document throws an XmlException. So does a document that has more than one root element, no root element, or a document type declaration (<!DOCTYPE ...>), which XmlEssentials never accepts.
View the complete sample on GitHub

Parse a stream without blocking

XmlDocument.ParseAsync reads a Stream of UTF-8 to its end with asynchronous reads and then parses what it read. It’s the counterpart of JsonDocument.ParseAsync.
The code produces the following output:
View the complete sample on GitHub What to notice:
  • It takes the same XmlDocumentOptions as Parse, and a CancellationToken. A canceled token cancels the task.
  • A null stream throws ArgumentNullException from the call itself, not from the task.
  • The stream isn’t closed. With MaxDocumentByteCount set, reading stops as soon as the stream is found to be longer than the limit.

Dispose the document

An XmlDocument rents its buffers from ArrayPool<T>.Shared. Dispose clears them and returns them. A document that you don’t dispose never returns its buffers, and the pool has to allocate new ones, so put every document in a using statement. An XmlElement doesn’t hold data. It holds a reference to its document and a position in it, so it’s usable only while the document is alive. Copy the values you need (strings, numbers, or a mutable copy) before the document is disposed.
The code produces the following output:
The rules for XmlElement:
  • Don’t return an XmlElement from a method that disposes the document, and don’t store one in a field that outlives the document.
  • Every member that reads from the document throws ObjectDisposedException after the document is disposed.
  • default(XmlElement) refers to no node. Its ValueKind is Undefined, and every other member that reads a node throws InvalidOperationException.
  • Two XmlElement values are equal when they point at the same node of the same document.

Find child elements and attributes

GetChild and GetAttribute return the node with the name you ask for and throw an XmlException when there isn’t one. TryGetChild and TryGetAttribute return false instead. Use the Get methods for what the document must contain and the Try methods for what’s optional.
The code produces the following output:
What to notice:
  • An attribute is an XmlElement too. Its ValueKind is Attribute, and you read its value with the same getters as an element.
  • The lookups search direct children only, and return the first match in document order. To go deeper, chain the calls: order.GetChild("Customer").GetChild("Name"). To search at any depth, write a recursive method over EnumerateChildren.
  • Names are case-sensitive, as XML requires.
View the complete sample on GitHub

Pass a name as characters or as UTF-8

GetChild, TryGetChild, GetAttribute and TryGetAttribute also take the name as a ReadOnlySpan<char> or as a ReadOnlySpan<byte> of UTF-8, as JsonElement.GetProperty and TryGetProperty do. Use them when the name is part of a longer string, or when you have it as a u8 literal.
The code produces the following output:
View the complete sample on GitHub These overloads match the local name in any namespace. To match one namespace, use the overloads that take a string.

Find names in a namespace

The one-argument lookups match the local name in any namespace. To match one namespace, pass its URI as the second argument. Pass an empty string for a name that is in no namespace. You never pass a prefix: prefixes are an author’s choice, and two documents can use different prefixes for the same namespace.
The code produces the following output:
What to notice:
  • An attribute without a prefix is in no namespace, even when its element is in a default namespace. That’s why href is found with an empty namespace URI.
  • Namespace declarations (xmlns and xmlns:prefix) are attributes of the element that declares them. AttributeCount and EnumerateAttributes include them.
  • GetChild, TryGetChild, and GetAttribute each have a namespace overload. TryGetAttribute has only the any-namespace form.
To list the namespaces a document declares, with their prefixes, call XmlDocument.DiscoverNamespaces. It reads the XML without building a document; see Take them from an existing document. For how namespaces work across the library, see Use XML namespaces.

Enumerate children and attributes

EnumerateChildren returns every child node of an element in document order, and EnumerateAttributes returns its attributes. Both work in a foreach statement.
The code produces the following output:
The loop skips every child that isn’t an element, and it has to. A document keeps the white space between elements and the comments, so the children of this indented Order are a Text node (the line break and indentation), an Item, another Text node, and so on. Check ValueKind in every loop over EnumerateChildren, or parse with WhitespaceHandling = XmlWhitespaceHandling.Insignificant and CommentHandling = XmlCommentHandling.Skip. GetChild, TryGetChild, and the attribute methods find elements and attributes by name and aren’t affected.
The enumerators are structs, like JsonElement.ArrayEnumerator, and enumerating doesn’t allocate. They don’t implement IEnumerable<T>, so LINQ operators such as Where and Select don’t apply to them. Filter inside the loop.

Check the kind of a node

Children aren’t always elements. XML allows text, CDATA sections, comments, and processing instructions between them, and a document keeps all of them by default, including the white space used for indentation. Check ValueKind when you enumerate.
The code produces the following output:
An element has one of three kinds. Element has a start tag and an end tag, EmptyElement is written as <Gift/>, and Nil carries xsi:nil="true". A test for elements has to accept all three, as the switch above does. child.ValueKind is XmlValueKind.Element alone skips empty and nil elements.
TokenType is the token a Utf8XmlReader reports for the same node, which is useful when code handles both. For a processing instruction, LocalName is the target.

Read typed values

The typed getters parse the value of an attribute, a text node, or an element. The value of an element is the text of all the text nodes and CDATA sections inside it.
The code produces the following output:
The getters follow the XML Schema lexical forms, not the current culture: What to notice:
  • The typed getters ignore white space around the value, so <Parcels> 3 </Parcels> is the integer 3. GetString returns " 3 ".
  • A failed conversion throws XmlException. It doesn’t throw FormatException. For a value that might not convert, use a TryGet method.
  • For a TimeSpan or an enum, call GetString and convert the result, or deserialize the element.
  • GetDateTime returns DateTimeKind.Utc for a value that ends in Z, Unspecified for a value with no time zone, and local time for any other offset. GetDateTimeOffset gives a value with no time zone the local offset. Use GetDateTimeOffset with explicit offsets when the result must not depend on the machine.
  • Name lookups, enumeration, and the numeric, Boolean, date, and GUID getters don’t allocate. Members that return a string or a byte[] allocate that result.

Read a value that might not convert

Each typed getter except GetBoolean and GetString has a TryGet counterpart, as JsonElement has: TryGetInt32, TryGetDouble, TryGetGuid, TryGetBytesFromBase64 and the rest. It returns false when the value isn’t in the form the type needs or doesn’t fit the type.
The code produces the following output:
View the complete sample on GitHub What to notice:
  • When a TryGet method returns false, the value it gives back is the default for the type.
  • A TryGet method throws where the getter throws for a reason other than the value: XmlException for a nil element, which has no value, and InvalidOperationException for a default XmlElement.

Read text and markup

Three methods return a node as a string, and they answer different questions.
The code produces the following output:
What to notice:
  • The text of an element includes the text of its descendants (today is inside <b>) and the content of CDATA sections. Comments and processing instructions inside the element don’t contribute.
  • That text includes white space between child elements when the document keeps it, which is the default. For <r>, a line break, two spaces, <c>x</c>, a line break, and </r>, the text of r is "\n x\n". Read values from the leaf elements that hold them (c here), where there is no surrounding white space to worry about.
  • Entity and character references are already expanded in GetString and GetInnerText. GetRawXml escapes the characters that markup requires.
  • GetRawXml builds the markup with a writer; it isn’t a slice of the original input. An attribute has no markup outside its element, so the result for an attribute is an empty string.

Handle nil elements

An element with xsi:nil="true" (or "1") says that it has no value, which is how XML Schema represents null. The document reports it with ValueKind equal to Nil and IsNil equal to true.
The code produces the following output:
Check IsNil before you call a typed getter on an element that can be nil. A typed getter on a nil element throws, because there is no value to convert. For how the serializer reads and writes nil, see Handle null and nil.

Read the XML declaration

Declaration is the <?xml ...?> declaration that the document started with, as an XmlDeclarationInfo, or null when the document had none.
The code produces the following output:
Version is 1.0 or 1.1. Encoding is always reported as utf-8, however the declaration spelled it. Standalone is null when the declaration leaves it out.

Keep, skip, or reject comments

A document keeps comments by default. The goal is no surprises on a round trip: a document that you parse and write back with WriteTo, for example a file that is edited and saved back to source control, still has its comments. XmlDocumentOptions.CommentHandling changes that. Set it to Skip when you don’t want comments in the document, or to Disallow to reject input that contains one.
CountChildren is a helper in the sample that counts the nodes EnumerateChildren returns. The code produces the following output:
Because comments are kept by default, EnumerateChildren can return Comment nodes for any document that has them. A loop that treats every child as an element must check ValueKind, or parse with CommentHandling = XmlCommentHandling.Skip.
default(XmlDocumentOptions), new XmlDocumentOptions(), and a call to Parse without options all mean the same options. Utf8XmlReader has the same defaults: it reports comments and white-space-only text between elements. XmlSerializer doesn’t; it skips both, because neither maps to a property. Comments and processing instructions before and after the root element aren’t children of anything you can reach from RootElement. The document keeps them and writes them in WriteTo.

Keep or drop white space between elements

A document also keeps text that consists only of white space between elements, which is what indentation is. The reason is the same as for comments: writing the document back keeps its layout. Each run of white space is a Text node among the children, and it’s part of the text of the element that contains it. Set WhitespaceHandling to Insignificant to leave that text out when you only read values.
The code produces the following output:
What to notice:
  • The setting is about text that is nothing but white space. White space inside a value is always kept: <Item> Keyboard </Item> has the value " Keyboard " under every setting.
  • Lookups by name and values of leaf elements (Item here) are the same under every setting.
  • White space outside the root element (after the declaration, around comments in the prolog, and the final line break) isn’t stored under any setting.

Set limits for untrusted input

XmlDocumentOptions carries the same limits as the reader. Each limit is a property whose value 0 means “use the default”.
The code produces the following output:
MaxDocumentByteCount is the one limit that is off by default. Because XmlDocument holds the whole document in memory, set it whenever the input comes from outside your process. With the Stream overload, reading stops as soon as the stream is found to be longer than the limit. A document that contains a document type declaration (<!DOCTYPE ...>) is rejected with “DTD is not allowed.”, so there are no entities to expand and nothing external to fetch. For the full threat model, see Security considerations.

Test input without an exception

TryParse returns false where Parse would throw an XmlException, which reads better than a try/catch when malformed input is an ordinary case. It takes UTF-8 bytes, and the options argument is required.
The code produces the following output:
A document that TryParse returns still has to be disposed. TryParse catches the exception for you, so it isn’t faster than Parse on bad input, and it doesn’t tell you what was wrong with the input; when you need the message and the position, call Parse and read them from the XmlException.

Parse one element from a reader

ParseValue builds a document from the element a Utf8XmlReader is positioned on: that element, its attributes, and everything inside it. Use it to read a large input forward with the reader and switch to random access for one record at a time, so only one record is in memory.
The code produces the following output:
What to notice:
  • When ParseValue returns, the reader is on the end tag of the element (or on the element itself, for an empty-element tag), so the next Read moves past it.
  • The document copies what it keeps. It doesn’t depend on the reader’s input after ParseValue returns.
  • The reader’s own XmlReaderOptions apply. ParseValue takes no XmlDocumentOptions.
  • If the reader reaches the end of its input without finding an element, ParseValue throws an XmlException with the message “The reader is not on an element and has none left to read.”.

When the input arrives in blocks

A reader that was created with isFinalBlock: false might be given only part of an element. ParseValue throws for an element that isn’t complete. TryParseValue returns false instead and leaves the reader where it was, so you can read more input and call it again. It’s the counterpart of JsonDocument.TryParseValue.
The code produces the following output:
View the complete sample on GitHub What to notice:
  • TryParseValue returns false in two cases: the element isn’t all in the block and the block isn’t the last one, or the reader is on an end tag.
  • XML that isn’t well formed still throws an XmlException, and so does an element that is cut short in the last block. The reader hasn’t moved when the exception leaves the method.
  • To go on after false, keep the bytes from BytesConsumed onward, add the next block, and create a reader with CurrentState, as Read a stream in blocks shows.
For the reader itself, see Use Utf8XmlReader.

Write a document

WriteTo writes the document to a Utf8XmlWriter: the declaration, the comments and processing instructions before the root, the root element, and whatever follows it.
The code produces the following output:
WriteTo writes what was parsed: comments, the white space between elements, namespace declarations where they were, prefixes as they were, attributes in their original order, and <c:Discontinued></c:Discontinued> and <c:Spare/> each in its own form. This document is already spelled the way the writer spells XML, so it comes back identical.

What a round trip keeps

With the default options, a round trip preserves the document’s content, its comments, and the indentation inside the root element. It doesn’t promise the same bytes, because the writer has one spelling for things XML lets authors spell several ways. Some of those spellings are set by XmlWriterOptions, and the rest are fixed. The next example parses a document that differs from the writer’s spelling in each of those ways.
The code produces the following output:
NewLine defaults to Environment.NewLine, so on Windows a document that was read with LF line ends is written with CRLF unless you set NewLine = "\n". To write the <Notes /> form, set EmptyElementStyle = XmlEmptyElementStyle.SelfClosingWithSpace. See Control the layout. View the complete sample on GitHub

Control the XML declaration

A document that was parsed without a declaration leaves the decision to the writer, and a Utf8XmlWriter writes a declaration unless XmlWriterOptions.OmitXmlDeclaration is true. A document that was parsed with a declaration always writes it, even to a writer that omits its own.
The code produces the following output:
The third line has a declaration although the writer was told to omit one, because the declaration belongs to the document. To write a parsed document without its declaration, write RootElement instead of the document, as the next section does.

Write one element

XmlElement.WriteTo writes one node and everything inside it, so you can copy part of a document into new markup.
The code produces the following output:
The c prefix was declared on the root of the source document, which isn’t part of what’s written. The writer adds the declaration to the copied element so the result is still correct. GetRawXml does the same when it returns a string.

Copy an element into the mutable tree

A document can’t be changed. When you need to edit what you parsed, CloneNode copies an element, its attributes, and its descendants into the mutable tree in CloudNimble.Text.Xml.Nodes. The copy owns its data, so it stays valid after the document is disposed.
The code produces the following output:
CloneNode returns the node type that matches the kind: an XmlElementNode for an element, an XmlTextNode for text, and so on. It makes every node under the element when it’s called, and each one is a heap object, so clone the smallest element you need to change. When you parse only to edit, call XmlNode.Parse instead: it keeps the parsed input with the tree and makes the nodes under an element only when you reach into it.

Deserialize from a document or an element

XmlSerializer.Deserialize accepts an XmlDocument or an XmlElement. That lets you look at a document first (check a version attribute, pick the elements you want) and then turn the parts you chose into objects.
Product.cs
The code produces the following output:
Deserializing from a document reads its root element. Each of these calls writes the element to a pooled buffer and reads that buffer, so when all you want is objects, deserialize from the original text or bytes and skip the document. The overloads that take an XmlTypeInfo<T> or an XmlSerializerContext work with source generation. The reverse direction is XmlSerializer.SerializeToDocument, which gives you a document to query without producing text in between:
The code produces the following output:
Dispose the document that SerializeToDocument returns. SerializeToElement returns the root element of a document that holds no pooled memory, so there’s nothing to dispose; it costs one more copy of the XML than SerializeToDocument. For everything else about the serializer, see Deserialize XML and Serialize XML.

Performance

XmlDocument stores one row per node in a pooled array, and names and values as offsets into its pooled copy of the input. It doesn’t create an object per node. In the project’s benchmarks against System.Xml.XmlDocument, on four real documents (an RSS feed, an OpenDocument file, a WordprocessingML file, and RPM metadata):
  • Parsing is 3.1× to 3.4× faster and allocates about 104 bytes, which is the XmlDocument object, where System.Xml.XmlDocument allocates 127 KB to 709 KB.
  • Writing a parsed document is 1.4× to 1.7× faster and allocates nothing.
See Benchmarks for the tables and the method. These numbers compare XmlDocument with System.Xml only. They say nothing about JsonDocument.

See also

Use XmlNode

Build and change XML with the mutable tree.

Use Utf8XmlReader

Read XML forward, one token at a time.

Use Utf8XmlWriter

Write XML to a buffer or a stream.

Migrate from XDocument and XmlDocument

Map System.Xml DOM code to XmlEssentials.

Security considerations

Limits and defaults for untrusted input.

Use XML namespaces

How names, prefixes, and URIs are handled.
API reference: