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 fromXmlNode, 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 anXmlElementNode 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.
ToStringreturns 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&. - An element that you create and give no children is written as an empty-element tag (
<Notes/>). SetIsEmptyElementtofalseto write it as<Notes></Notes>. A parsed element keeps the form it had in its source. - Setting
InnerTextreplaces all the children of the element with one text node. Setting it to an empty string removes them.
Parse XML into a tree
XmlNode.Parse reads a document from a string or from UTF-8 bytes and returns its root element.
- 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.IsEmptyElementholds 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:
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.
Navigate the tree
The indexer on an element returns the first child element with a local name, ornull. Children and Attributes are lists that you index, count, and enumerate. Parent goes back up.
- A missing name gives
null, not an exception. That’s different fromXmlElement.GetChild, which throws. order["Item"]returns only the firstItem. To visit every match, enumerateChildrenand filter, as the loop does.Childrenholds 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 asChildren[0]to find an element. Use the name indexer, a type pattern (child is XmlElementNode), orValueKind.- An
XmlElementNodeis itself anIEnumerable<XmlNode>over its children, soforeach (XmlNode child in order)and LINQ operators such asOfType<XmlElementNode>()work on it. InnerTexton an element that has child elements includes the white space between them. Read it from the elements that hold the values, such asCustomer.order["Item", "urn:example"]andorder.Attributes["sku", "urn:example"]match a namespace URI as well. The one-argument forms match the local name in any namespace.InnerTextis 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.
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.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.
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 anXmlException; 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.
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.
- 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
nullvalue is stored as an empty string. To delete an attribute, remove it from the list. Attributes.Adddoesn’t check for a duplicate name. Two attributes with the same name fail when the tree is written, with “Duplicate attribute.”.SetAttributeavoids the problem.
Use namespaces
An element or an attribute has aNamespaceUri 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.
- 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
AddElementfor 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 withxmlns="". - In the first output,
dcis 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 namedc, prefixxmlns, and namespaceXmlNamespaces.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
NamespaceUriproperty. Changing a declaration attribute doesn’t move elements to another namespace.
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.- 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.
InnerTextjoins the text nodes and the CDATA sections and skips comments and processing instructions.- The
ValueKindof an element in the tree is alwaysElement. TheEmptyElementandNilkinds are reported only byXmlElement.
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.
XmlDeclarationNode, for when you need to state the declaration yourself.
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.XmlWriterOptions properties name the style:
See Control the layout. There are limits:
- White space and comments outside the root element aren’t kept.
XmlNode.Parsereturns 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
OmitXmlDeclarationistrue. 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
Ais 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.
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
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.XmlDocumentkeeps 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, besideSystem.Xml.XmlDocument,XDocument, andJsonNode.XmlNode.Parseparses into anXmlDocumentand 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.CloneNodemakes 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.
- To read values, parse with
XmlDocumentand 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, aStream, or the typed getters ofXmlElementto find what to change, parse withXmlDocumentand callCloneNodeon the element you change. - To produce XML with a fixed shape at high volume, write it with
Utf8XmlWriteror serialize a class. Both skip the tree.
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.