Skip to main content
The types in the CloudNimble.Text.Xml.Nodes namespace are a tree of XML nodes that you can change: add an element, set an attribute, remove a comment, and write the result. Use them when you edit a document or assemble one piece by piece and a class to serialize would be more than you need. XmlNode is the XML counterpart of JsonNode in System.Text.Json: a mutable tree that sits beside a read-only document type. The shape is different, because XML isn’t a property bag. An element has an ordered list of children that can mix elements, text, comments, and more, and a separate list of attributes, where a JsonObject has one value per name.

Choose between the mutable tree and the document

If you only read, use XmlDocument. If you read forward once through a large input, use Utf8XmlReader. If the XML maps to your own classes, use XmlSerializer. The cost of the tree is covered in When the tree costs more at the end of this page.

The node types

Every type derives from XmlNode, which has three members that all nodes share: ValueKind, Parent, and NamespaceUri (which is null for nodes that have no name). XmlElementNode.Children is an XmlNodeList and XmlElementNode.Attributes is an XmlAttributeNodeList. Both implement IList<T>.

Build a tree

Create an XmlElementNode and add to it. SetAttribute adds an attribute, AddElement creates a child element and returns it, Add appends any node, and setting InnerText gives an element its text.
The code produces the following output:
What to notice:
  • ToString returns the markup of the node, without an XML declaration and without indentation.
  • You set values as plain text. Escaping happens when the tree is written, so & became &amp;.
  • An element that you create and give no children is written as an empty-element tag (<Notes/>). Set IsEmptyElement to false to write it as <Notes></Notes>. A parsed element keeps the form it had in its source.
  • Setting InnerText replaces all the children of the element with one text node. Setting it to an empty string removes them.
View the complete sample on GitHub

Parse XML into a tree

XmlNode.Parse reads a document from a string or from UTF-8 bytes and returns its root element.
The code produces the following output:
The tree holds the root element and what’s inside it. Compare the output with the input:
  • Kept: elements, attributes, text, CDATA sections, processing instructions inside the root, and comments inside the root.
  • Kept: the white space between elements inside the root, as text nodes, so the indentation survives. The goal is the same as for XmlDocument: no surprises when a document is edited and saved.
  • Dropped: the XML declaration, and the comments, processing instructions, and white space before and after the root element.
  • Kept: the form of an element with no content. <Notes></Notes> comes back as <Notes></Notes>, and <Notes/> would come back as one tag. XmlElementNode.IsEmptyElement holds the form, and you can set it.
Parse returns the root as an XmlNode; cast the result to XmlElementNode to reach the element members. Input that isn’t a well-formed document throws an XmlException. Parse takes a string or UTF-8 bytes and uses the default XmlDocumentOptions. When you need other limits, a tree without the white space, or input from a Stream, parse with XmlDocument and call CloneNode on the element you want. The copy is complete when CloneNode returns, so it stays valid after the document is disposed:
The code produces the following output:
View the complete sample on GitHub

How a parsed tree is built

XmlNode.Parse and XmlNode.ParseValue keep the parsed input with the tree, as JsonNode.Parse does. An element makes its attributes and child nodes the first time you reach into it, for example through Children, Attributes, or InnerText, or by changing it. Until then, it’s written and copied straight from the parsed input. You can’t tell the difference from what the tree reads or writes. A tree is written the same however much of it you have reached into, and an element you move to another tree declares the namespaces it needs either way. DeepClone of an element you haven’t reached into gives a tree of its own: changing the copy leaves the original alone, and the other way round. The parsed input stays in memory as long as an element that you haven’t reached into is reachable, including one that you moved into another tree or copied with DeepClone. It doesn’t depend on your string, array, or reader after Parse or ParseValue returns. XmlElement.CloneNode works differently: it copies everything under the element at once, because you dispose the document it came from.

Parse one element from a reader

XmlNode.ParseValue builds a tree from the element a Utf8XmlReader is positioned on, and leaves the reader on that element’s end tag. Use it to edit one record of a large input at a time.
The code produces the following output:
The indexer on an element returns the first child element with a local name, or null. Children and Attributes are lists that you index, count, and enumerate. Parent goes back up.
The code produces the following output:
What to notice:
  • A missing name gives null, not an exception. That’s different from XmlElement.GetChild, which throws.
  • order["Item"] returns only the first Item. To visit every match, enumerate Children and filter, as the loop does.
  • Children holds every kind of node, and in a tree parsed from an indented document that includes a text node for each run of indentation: four of the seven children here. Don’t rely on positions such as Children[0] to find an element. Use the name indexer, a type pattern (child is XmlElementNode), or ValueKind.
  • An XmlElementNode is itself an IEnumerable<XmlNode> over its children, so foreach (XmlNode child in order) and LINQ operators such as OfType<XmlElementNode>() work on it.
  • InnerText on an element that has child elements includes the white space between them. Read it from the elements that hold the values, such as Customer.
  • order["Item", "urn:example"] and order.Attributes["sku", "urn:example"] match a namespace URI as well. The one-argument forms match the local name in any namespace.
  • InnerText is the text of every text node and CDATA section inside the element, at any depth. Values are strings; the tree has no typed getters, so convert them yourself.

Add and insert nodes

AddElement and Add append. To put a node at a position, call Insert on the Children list.
The code produces the following output:

Indentation when you add nodes

The tree doesn’t indent for you. In a tree parsed from an indented document, the indentation is ordinary text nodes, and a node you add goes exactly where you put it, with no white space around it. You have three choices: accept the result, add the white-space text nodes yourself, or work without the white space and let the writer indent the output.
The code produces the following output:
The first result keeps the original indentation and puts the new Item after the last line break, right before the end tag. The second and third come from a tree without white space, parsed through XmlDocument with WhitespaceHandling.Insignificant, written compact and then with an indenting writer. Use the third approach when you’re free to reformat the document, and the first, with your own white-space text nodes, when the rest of the file must stay as it was.

Remove, replace, and move nodes

Remove and RemoveAt take a node out of a list, and assigning to an index replaces the node at that position. A node that is removed or replaced has no parent afterward, so you can add it somewhere else.
The code produces the following output:
Clear removes every node from a list. Don’t change a list while a foreach loop is enumerating it. After a node is added, removed, or replaced, the loop’s next step throws an InvalidOperationException (“Collection was modified; enumeration operation may not execute.”), which is what a List<T> and a JsonArray do. Loop over a copy, or loop by index from the end:

Copy a node with DeepClone

A node has at most one parent. Adding a node that already has one throws an XmlException; it isn’t moved for you. To put the same content in two places, add a copy. DeepClone copies a node with its attributes and descendants, and the copy has no parent.
The code produces the following output:
The copy is independent: changing its sku left the original alone.

Work with attributes

SetAttribute changes the value of an attribute that exists and appends one that doesn’t. The Attributes list gives you the attribute nodes themselves, to read, change, reorder, or remove.
The code produces the following output:
What to notice:
  • Attributes are written in list order. A changed attribute keeps its position, and a new one goes last.
  • SetAttribute(name, value) sets the attribute with that local name in no namespace, and leaves an attribute with the same local name in another namespace as it is. Pass the namespace URI as the third argument for an attribute in a namespace.
  • A null value is stored as an empty string. To delete an attribute, remove it from the list.
  • Attributes.Add doesn’t check for a duplicate name. Two attributes with the same name fail when the tree is written, with “Duplicate attribute.”. SetAttribute avoids the problem.

Use namespaces

An element or an attribute has a NamespaceUri and a Prefix. Set the namespace to say what the name means, and set the prefix when you care how it’s spelled. The writer adds the xmlns declarations that the names need.
The code produces the following output:
What to notice:
  • An element with a namespace and no prefix is written with a default namespace declaration (xmlns="...").
  • A child doesn’t inherit its parent’s namespace. Pass the namespace to AddElement for every element that belongs to it. A child that you create without one is in no namespace, and under a default namespace it’s written with xmlns="".
  • In the first output, dc is declared on each element that uses it, because nothing above them declares it. To declare a prefix once, add a namespace declaration to an ancestor as an attribute: local name dc, prefix xmlns, and namespace XmlNamespaces.Xmlns. The second output shows the result.
  • A tree that you parse already has its declarations as attributes like that one, so it’s written back with the declarations where they were.
  • The namespace of an element or attribute comes from its NamespaceUri property. Changing a declaration attribute doesn’t move elements to another namespace.
When a name has a namespace and no prefix to carry it, the writer makes one up. When a name has a prefix and no namespace, the tree can’t be written:
The code produces the following output:
An attribute needs a prefix to be in a namespace, because an attribute without one is in no namespace. Construct an XmlAttributeNode with the prefix you want when ns1 isn’t acceptable. For the rules across the library, see Use XML namespaces.
The tree doesn’t validate as you build it. The constructors and the name setters reject only a null, empty, or white-space name or processing instruction target. Everything else about names, prefixes, and values is checked when the tree is written: an invalid name, a duplicate attribute, a comment that contains --, or a CDATA section that contains ]]> throws an XmlException from ToString or WriteTo, not from the call that created the node.

Add text, CDATA, comments, and processing instructions

An element’s children can be any mix of node types, in any order.
The code produces the following output:
What to notice:
  • A text node is escaped when it’s written. A CDATA section is written as is, which is its purpose: text with markup characters that you don’t want escaped.
  • InnerText joins the text nodes and the CDATA sections and skips comments and processing instructions.
  • The ValueKind of an element in the tree is always Element. The EmptyElement and Nil kinds are reported only by XmlElement.

Write the tree

ToString is the short way to get markup. For control over the output, or to write to a stream or a buffer without a string in between, pass a Utf8XmlWriter to WriteTo. The writer’s options decide the declaration and the indentation.
The code produces the following output:
The first writer adds the XML declaration itself, which is what you want in most cases. The second part shows XmlDeclarationNode, for when you need to state the declaration yourself.
XmlDeclarationNode.WriteTo writes the declaration and tells the writer that one is there, so the writer doesn’t add its own, whatever OmitXmlDeclaration is set to. Write the node first. A declaration node can’t be added to an element’s Children: that throws an XmlException.
XmlNode.Parse never produces an XmlDeclarationNode, and a tree has no document node to hold one. The declaration of a parsed document is available on XmlDocument.Declaration.

Change one thing in a file and write it back

To edit a file and leave the rest of it as it was, parse it, make the change, and write the tree with options that name the file’s style. The tree keeps the white space and the comments inside the root element, and whether each element with no content had one tag or two. The writer’s options set the rest.
The code produces the following output:
View the complete sample on GitHub The version number is the only difference from the input. These XmlWriterOptions properties name the style: See Control the layout. There are limits:
  • White space and comments outside the root element aren’t kept. XmlNode.Parse returns the root element, so a comment before it and a line break after its end tag aren’t in the tree.
  • The writer adds an XML declaration unless OmitXmlDeclaration is true. The declaration the file had isn’t in the tree, so the one that is written is the writer’s: <?xml version="1.0" encoding="utf-8"?>.
  • A few spellings have no setting. Attribute values are written in double quotes, extra white space inside a tag isn’t kept, and a character reference such as &#65; is written as the character. See What a round trip keeps.

Call ToString on other nodes

ToString works on any node that can stand alone at the top of a document. Text and attributes can’t.
The code produces the following output:
To see a text node or an attribute while you debug, read its Value.

Serialize to and from nodes

XmlSerializer.SerializeToNode turns an object into a tree, and XmlSerializer.Deserialize accepts a node. Together they let you adjust the XML of an object before it’s written, or adjust XML before it becomes an object.
Product.cs
The code produces the following output:
Both calls go through UTF-8: SerializeToNode serializes to a pooled buffer and parses it into a tree, and Deserialize writes the node to a pooled buffer and reads it. They’re a convenience, not a faster path than text. Both have overloads that take an XmlTypeInfo<T> or an XmlSerializerContext for source generation. For the serializer itself, see Serialize XML and Deserialize XML.

When the tree costs more

The read-only document and the mutable tree store XML in different ways, and the difference matters when documents are large or frequent.
  • XmlDocument keeps one pooled copy of the input and a pooled table of rows. Parsing allocates the document object and nothing per node. See Benchmarks for the measured numbers of both, beside System.Xml.XmlDocument, XDocument, and JsonNode.
  • XmlNode.Parse parses into an XmlDocument and keeps it, outside the pool, for the tree. An element you reach into gets an object for each of its attributes and child nodes, with a string for each name and value. The elements you never reach into stay as rows of the parsed input. So the work and the memory grow with the part of the tree you look at, and the parsed input stays in memory while any of those elements is reachable.
  • XmlElement.CloneNode makes every node under the element at once.
  • Writing an element you have reached into converts its strings back to UTF-8. Writing an element you haven’t reached into, or a document, writes from the parsed input.
So:
  • To read values, parse with XmlDocument and don’t build a tree.
  • To change a document, part of it or all of it, or to build one, use the tree. That’s what it’s for.
  • When the change needs XmlDocumentOptions, a Stream, or the typed getters of XmlElement to find what to change, parse with XmlDocument and call CloneNode on the element you change.
  • To produce XML with a fixed shape at high volume, write it with Utf8XmlWriter or serialize a class. Both skip the tree.
Several threads can read a tree at once while no thread is changing it, as they can a JsonNode tree. A parsed tree makes an element’s attributes and child nodes the first time something reaches into it, and threads that reach in at the same moment all get the same nodes. Changes aren’t synchronized: while one thread changes a tree, no other thread can use it. See Thread safety.

See also

Use XmlDocument

Read XML with the read-only, pooled document.

Use Utf8XmlWriter

Control how a tree is written.

Use XML namespaces

How names, prefixes, and URIs are handled.

Migrate from XDocument and XmlDocument

Map System.Xml DOM code to XmlEssentials.
API reference: