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.- The document is in a
usingstatement. AnXmlElementis a view into the document’s buffers, and it throwsObjectDisposedExceptionafter the document is disposed. EnumerateChildrenreturns every child node, and in this indented document that includes the white space between elements. The loop keeps the nodes whoseValueKindisElementand whose name matches.Elements("Shelf")did both for you.GetChildandGetAttributethrow anXmlExceptionwhen the name isn’t found. Where LINQ to XML code tests fornull, callTryGetChildorTryGetAttribute.- A cast becomes a method:
(int)attributeisGetInt32(), and(string)elementisGetString().
Member mapping
The table lists the LINQ to XML member, theSystem.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 noXNametype to build withns + "Title". XElement.SetAttributeValue(name, null)removes the attribute.XmlElementNode.SetAttribute(name, null)stores an empty string. To remove an attribute, callAttributes.Remove.XmlElement.GetString()on an element returns its text content. It returnsnullonly when the element hasxsi:nil="true".XmlElementis a struct.default(XmlElement)refers to no node, and itsValueKindisUndefined.
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:
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
XmlDocumentOptionswithWhitespaceHandling = XmlWhitespaceHandling.Insignificant, andCommentHandling = XmlCommentHandling.Skipif you don’t want comments either. The document then holds elements and text only.
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"):
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
Change a document
To change XML, parse it withXmlNode.Parse, which returns the root element of a mutable tree. The following pair renames a shelf, adds a book, and removes one.
- There is no functional construction. You create a node and then add to it.
AddElementreturns the new element, so calls chain. - Attribute values and text are strings. LINQ to XML converts
4and1951for you; here you write"4"and"1951". - A node is removed through its parent’s
Childrenlist. A node has noRemovemethod of its own. ToStringwrites the element without a declaration and without adding indentation.XElement.ToString()indents unless you passSaveOptions.DisableFormatting.XDocument.Parsebuilds every node before it returns.XmlNode.Parsekeeps 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.
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.
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.