Skip to main content
This article is for developers who load XML into XDocument and XElement (LINQ to XML) or into System.Xml.XmlDocument, and want to move that code to XmlEssentials. It shows which XmlEssentials type replaces which use, maps the members you call, and lists what isn’t there. XmlEssentials has two document models where System.Xml has one for each API, and they follow System.Text.Json: XmlDocument and XmlElement correspond to JsonDocument and JsonElement, and the XmlNode types in CloudNimble.Text.Xml.Nodes correspond to JsonNode. Which one you choose matters for speed. In the project’s benchmarks, the read-only XmlDocument parses four real documents 3.1× to 3.4× faster than System.Xml.XmlDocument and allocates 104 bytes for each. The mutable tree parses 1.5× faster than System.Xml.XmlDocument and XDocument, but XDocument is faster at parsing, changing, and writing a whole document.
CloudNimble.Text.Xml.XmlDocument, XmlElement, and Nodes.XmlNode share their names with types in System.Xml. A file that imports both namespaces needs an alias or a fully qualified name. During a migration, move one file at a time and remove using System.Xml; from it.

Choose the replacement

You can combine the two models. XmlElement.CloneNode() copies one element of a read-only document into the mutable tree, and both models write themselves to a Utf8XmlWriter.

Table of differences

Read a document

The following pair loads a library document, lists the shelves and books, reads an attribute as a number, and checks for an element that isn’t there.
Both read this document:
Both produce the following output:
What changed:
  • The document is in a using statement. An XmlElement is a view into the document’s buffers, and it throws ObjectDisposedException after the document is disposed.
  • EnumerateChildren returns every child node, and in this indented document that includes the white space between elements. The loop keeps the nodes whose ValueKind is Element and whose name matches. Elements("Shelf") did both for you.
  • GetChild and GetAttribute throw an XmlException when the name isn’t found. Where LINQ to XML code tests for null, call TryGetChild or TryGetAttribute.
  • A cast becomes a method: (int)attribute is GetInt32(), and (string)element is GetString().
View the complete sample on GitHub

Member mapping

The table lists the LINQ to XML member, the System.Xml.XmlDocument member that does the same job, and the XmlEssentials member in each model. Details that differ from what the member names suggest:
  • Where a member takes a name, a second overload takes a namespace URI: GetChild("Title", "urn:contoso:books"). There is no XName type to build with ns + "Title".
  • XElement.SetAttributeValue(name, null) removes the attribute. XmlElementNode.SetAttribute(name, null) stores an empty string. To remove an attribute, call Attributes.Remove.
  • XmlElement.GetString() on an element returns its text content. It returns null only when the element has xsi:nil="true".
  • XmlElement is a struct. default(XmlElement) refers to no node, and its ValueKind is Undefined.

Comments and white space

XmlDocument.Parse and XmlNode.Parse keep comments and keep the white space between elements, so a document that you parse and write back keeps its comments and indentation. XDocument.Parse and System.Xml.XmlDocument.Load also keep comments, but they drop white space between elements unless you ask for it with LoadOptions.PreserveWhitespace or PreserveWhitespace = true. The XmlEssentials default is the same as those settings. The consequence for migrated code is in the child count:
Program.cs
CountChildren is a helper in the sample that counts what EnumerateChildren returns. The code produces the following output:
With the default options, Order has five children: white space, the comment, white space, Item, and white space. XDocument.Parse with its defaults gives two, the comment and Item. Choose one of these when you move code that walks child nodes:
  • Filter on ValueKind, as the samples on this page do. The document still round-trips.
  • Pass XmlDocumentOptions with WhitespaceHandling = XmlWhitespaceHandling.Insignificant, and CommentHandling = XmlCommentHandling.Skip if you don’t want comments either. The document then holds elements and text only.
The round trip keeps the document’s content, not every byte of its formatting. Details that aren’t part of the XML data, such as the quote character around an attribute value, are written in the writer’s own style. Three of them are set by XmlWriterOptions: NewLine is the line ending of the whole output, which is why the sample sets it; EmptyElementStyle is the form of an empty-element tag, where XmlEmptyElementStyle.SelfClosingWithSpace gives the <Item /> that XDocument writes; and AttributeStyle is the layout of attributes. See Use XmlDocument. View the complete sample on GitHub

Queries

LINQ to XML is a query API: Descendants, Ancestors, ElementsAfterSelf, and the other axis methods return sequences that you compose with LINQ. System.Xml.XmlDocument has SelectNodes and SelectSingleNode for XPath. XmlEssentials has neither. XmlElement.EnumerateChildren returns a struct enumerator that works in foreach and doesn’t implement IEnumerable<T>, so LINQ operators don’t apply to it. For a search at any depth, write the recursion. This is the replacement for document.Descendants("Title"):
Both produce the following output:
An element has one of three kinds: Element when it has a start tag and an end tag, EmptyElement when it’s written as one tag (<Item/>), and Nil when it carries xsi:nil="true". Test for every kind that can occur in your documents. GetString returns null for a nil element. In the mutable tree, XmlElementNode.Children is an IList<XmlNode>, so LINQ to Objects works on one level at a time. The next section uses OfType<XmlElementNode>() and First that way. View the complete sample on GitHub
If a query reads many values from one document into objects, XmlSerializer.Deserialize usually replaces the query and the object construction together.

Change a document

To change XML, parse it with XmlNode.Parse, which returns the root element of a mutable tree. The following pair renames a shelf, adds a book, and removes one.
Both produce the following output:
What changed:
  • There is no functional construction. You create a node and then add to it. AddElement returns the new element, so calls chain.
  • Attribute values and text are strings. LINQ to XML converts 4 and 1951 for you; here you write "4" and "1951".
  • A node is removed through its parent’s Children list. A node has no Remove method of its own.
  • ToString writes the element without a declaration and without adding indentation. XElement.ToString() indents unless you pass SaveOptions.DisableFormatting.
  • XDocument.Parse builds every node before it returns. XmlNode.Parse keeps the parsed input and makes the nodes under an element when you first reach into it, and an element that nothing reaches into is written straight from the input. See How a parsed tree is built.
The input in this sample is on one line. XmlNode.Parse keeps white space between elements, so in an indented document the new Book element would follow the old indentation text without any of its own. View the complete sample on GitHub

Save a document

XDocument.Save and System.Xml.XmlDocument.Save take a stream, a TextWriter, a file name, or an XmlWriter. In XmlEssentials, both models write to a Utf8XmlWriter, and the writer’s options control the declaration and the indentation.
The XmlEssentials code produces the following output:
XDocument.Save writes the same text, preceded by a UTF-8 byte order mark. Utf8XmlWriter writes one only when XmlWriterOptions.EmitByteOrderMark is true. View the complete sample on GitHub

What isn’t supported

See also

Use XmlDocument

The complete guide to the read-only model.

Use XmlNode

The complete guide to the mutable tree.

Deserialize

Read XML into your own types.

Namespaces

Names, prefixes, and URIs.

Migrate from XmlReader and XmlWriter

Move low-level reading and writing code.

XML conformance

What the parser accepts and rejects.
API reference: