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.
RootElementis the document element. It’s where every query starts.- When you already have UTF-8 bytes, pass them as bytes. The
stringandReadOnlySpan<char>overloads convert the text to UTF-8 first. - The
Streamoverload reads the stream to its end and doesn’t close it. To read the stream without blocking, useParseAsync. - 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.
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.
- It takes the same
XmlDocumentOptionsasParse, and aCancellationToken. A canceled token cancels the task. - A
nullstream throwsArgumentNullExceptionfrom the call itself, not from the task. - The stream isn’t closed. With
MaxDocumentByteCountset, reading stops as soon as the stream is found to be longer than the limit.
Dispose the document
AnXmlDocument 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.
XmlElement:
- Don’t return an
XmlElementfrom 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
ObjectDisposedExceptionafter the document is disposed. default(XmlElement)refers to no node. ItsValueKindisUndefined, and every other member that reads a node throwsInvalidOperationException.- Two
XmlElementvalues 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.
- An attribute is an
XmlElementtoo. ItsValueKindisAttribute, 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 overEnumerateChildren. - Names are case-sensitive, as XML requires.
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.
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.- An attribute without a prefix is in no namespace, even when its element is in a default namespace. That’s why
hrefis found with an empty namespace URI. - Namespace declarations (
xmlnsandxmlns:prefix) are attributes of the element that declares them.AttributeCountandEnumerateAttributesinclude them. GetChild,TryGetChild, andGetAttributeeach have a namespace overload.TryGetAttributehas only the any-namespace form.
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.
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. CheckValueKind when you enumerate.
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.
What to notice:
- The typed getters ignore white space around the value, so
<Parcels> 3 </Parcels>is the integer3.GetStringreturns" 3 ". - A failed conversion throws
XmlException. It doesn’t throwFormatException. For a value that might not convert, use aTryGetmethod. - For a
TimeSpanor an enum, callGetStringand convert the result, or deserialize the element. GetDateTimereturnsDateTimeKind.Utcfor a value that ends inZ,Unspecifiedfor a value with no time zone, and local time for any other offset.GetDateTimeOffsetgives a value with no time zone the local offset. UseGetDateTimeOffsetwith 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
stringor abyte[]allocate that result.
Read a value that might not convert
Each typed getter exceptGetBoolean 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.
- When a
TryGetmethod returnsfalse, the value it gives back is the default for the type. - A
TryGetmethod throws where the getter throws for a reason other than the value:XmlExceptionfor a nil element, which has no value, andInvalidOperationExceptionfor a defaultXmlElement.
Read text and markup
Three methods return a node as a string, and they answer different questions.- The text of an element includes the text of its descendants (
todayis 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 ofris"\n x\n". Read values from the leaf elements that hold them (chere), where there is no surrounding white space to worry about. - Entity and character references are already expanded in
GetStringandGetInnerText.GetRawXmlescapes the characters that markup requires. GetRawXmlbuilds 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 withxsi: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.
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.
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 withWriteTo, 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:
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 aText 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.
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 (
Itemhere) 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”.
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.
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.
- When
ParseValuereturns, the reader is on the end tag of the element (or on the element itself, for an empty-element tag), so the nextReadmoves past it. - The document copies what it keeps. It doesn’t depend on the reader’s input after
ParseValuereturns. - The reader’s own
XmlReaderOptionsapply.ParseValuetakes noXmlDocumentOptions. - If the reader reaches the end of its input without finding an element,
ParseValuethrows anXmlExceptionwith 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 withisFinalBlock: 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.
TryParseValuereturnsfalsein 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 fromBytesConsumedonward, add the next block, and create a reader withCurrentState, as Read a stream in blocks shows.
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.
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 byXmlWriterOptions, and the rest are fixed. The next example parses a document that differs from the writer’s spelling in each of those ways.
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 aUtf8XmlWriter 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.
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.
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.
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
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:
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
XmlDocumentobject, whereSystem.Xml.XmlDocumentallocates 127 KB to 709 KB. - Writing a parsed document is 1.4× to 1.7× faster and allocates nothing.
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.