Chilkat.Xml Class Overview

Chilkat.Xml provides DOM-style XML parsing, navigation, construction, editing, searching, sorting, serialization, and utility operations. It can load XML from strings, files, BinData, or StringBuilder; traverse and modify XML trees; manage attributes and content; handle namespaces, CDATA, binary content, compression, encryption, entity decoding, and XML output formatting.

What the Class Is Used For

Use Chilkat.Xml when an application needs direct, editable access to an XML document or subtree. Each Xml object references a node in an XML tree. From that node, the application can inspect tag names, content, attributes, children, parents, siblings, and descendants, or modify the tree by adding, updating, extracting, removing, sorting, swapping, zipping, encrypting, and saving nodes.

Parse and Emit XML Load XML from memory or files and emit compact or formatted XML to strings, files, BinData, or StringBuilder.
Navigate XML Trees Move through children, siblings, parents, the document root, or search results using reference-returning and reference-updating methods.
Edit Nodes and Attributes Create child nodes, update content, add or remove attributes, extract subtrees, scrub text, and prune tags or attributes.
Handle Binary Content Store binary data as base64, optionally zip-compress or AES-encrypt it, then restore or save the original bytes later.

Typical Workflow

  1. Load XML with LoadXml, LoadXml2, LoadXmlFile, LoadXmlFile2, LoadBd, or LoadSb.
  2. Inspect the current node using Tag, Content, NumChildren, NumAttributes, and namespace-related properties.
  3. Navigate with methods such as FindChild, GetChild, FirstChild, NextSibling, GetParent, or GetRoot.
  4. Read values with methods such as GetChildContent, GetChildIntValue, GetAttrValue, and TagContent.
  5. Modify the document with NewChild, UpdateChildContent, UpdateAttrAt, AddOrUpdateAttribute, or removal methods.
  6. Search, sort, scrub, prune, compress, encrypt, or transform content as needed.
  7. Save or emit the result with GetXml, GetXmlSb, GetXmlBd, or SaveXml.

Core Concepts

Concept Meaning Important Members
XML Node Reference A Xml object references one node in an XML tree. Many methods return a new object referencing another node, while methods ending in 2 often update the caller’s internal reference. CopyRef, GetSelf, FindChild2, GetRoot2
Tree / Document The complete XML tree. Any node can find the root, and TreeId identifies which XML tree a node belongs to. TreeId, GetRoot, GetRoot2, RemoveFromTree
Tag Path A vertical-bar-delimited path of child tags, such as colors|primary|red. Many child methods accept either a simple tag or a tag path. FindChild, GetChildContent, UpdateChildContent, UpdateAt
Attributes Name/value pairs stored on a node’s start tag. NumAttributes, AddAttribute, GetAttrValue, RemoveAttribute
Content Text directly contained by the node, excluding child nodes. Content, ContentInt, AppendToContent, UpdateChildContent
Namespace Prefix A tag may include a namespace prefix, such as soapenv:Envelope. The prefix and unprefixed tag can be accessed separately. Tag, TagNsPrefix, TagUnprefixed, TagNsEquals

Core Properties

Property Purpose Guidance
Tag Gets or sets the node’s tag, including namespace prefix. Example: soapenv:Body.
TagNsPrefix Namespace prefix portion of the tag. For soapenv:Envelope, returns soapenv.
TagUnprefixed Tag name without namespace prefix. For soapenv:Envelope, returns Envelope.
Content Text directly contained by the node. Child node text is not included in this value.
ContentInt Gets or sets node content as an integer. Useful for counters or numeric XML fields.
Cdata Controls whether the node content is emitted as a CDATA section. Use when content should be preserved as character data.
NumChildren Number of direct child nodes. Use with GetChild or GetChild2 for direct child iteration.
NumAttributes Number of attributes on the node. Use with GetAttributeName and GetAttributeValue.
TagPath Path from the XML document root to the current element. Empty when the caller is the document root.
TreeId Unique ID for the XML tree. Helps determine whether two Xml objects belong to the same document tree.

Loading and Saving XML

Task Methods Notes
Load XML from string LoadXml, LoadXml2 Replaces the caller’s contents with the loaded document root. LoadXml2 adds an autoTrim option.
Load XML from file LoadXmlFile, LoadXmlFile2 Loads XML from disk. The *2 variant controls trimming of leaf-node content.
Load from memory objects LoadBd, LoadSb Loads XML from BinData or StringBuilder.
Emit XML as text GetXml Returns XML text for the tree rooted at the current node. The XML declaration is included only when called from the document root.
Emit to memory objects GetXmlBd, GetXmlSb Appends emitted XML to BinData or StringBuilder.
Save to file SaveXml Writes XML for the tree or subtree rooted at the current node.

Output Formatting and XML Declaration

Property Controls Important Detail
EmitCompact Whether GetXml and GetXmlSb emit compact XML. Default is false. When true, unnecessary whitespace and line endings are omitted.
EmitXmlDecl Whether the XML declaration is emitted. Default is true. Set false to omit the <?xml ... ?> line.
EmitBom Whether files are written with a byte order mark. Applies to writing XML files, not to GetXml. Default is false.
Encoding The encoding attribute in the XML declaration. Default is utf-8. Setting it changes the declaration value; it does not convert the document to a different encoding.
Standalone The standalone attribute in the XML declaration. When true, emits standalone="yes".
DocType DOCTYPE declaration. Gets or sets the document type declaration when present.
Encoding reminder: Encoding controls the XML declaration’s encoding attribute. It does not by itself convert already-loaded XML content to a different byte encoding.

Navigation Patterns

Navigation Need Returning Methods Reference-Updating Methods
First or last child FirstChild, LastChild FirstChild2, LastChild2
Nth child GetChild GetChild2
Child by tag or tag path FindChild, GetChildWithTag FindChild2, GetChildWithTag2
Nth child with a tag GetNthChildWithTag GetNthChildWithTag2
Parent GetParent GetParent2
Document root GetRoot GetRoot2
Next or previous sibling NextSibling, PreviousSibling NextSibling2, PreviousSibling2
Depth-first traversal Not applicable. NextInTraversal2
Method naming pattern: Many methods ending in 2 update the caller’s internal node reference instead of returning a new Xml object. This can reduce object creation but requires care because the caller now points somewhere else in the tree.

Tag Paths and ChilkatPath

Many methods accept a tag path, which is a series of tags separated by vertical bars, such as Envelope|Body|Request. This is different from standard XPath.

Feature Member Purpose
Index substitution I, J, K Values substituted for [i], [j], and [k] in tag paths and ChilkatPath.
Simple child path tagA|tagB|tagC Navigates down direct child elements by tag name.
ChilkatPath command language ChilkatPath Navigates through nodes and returns content, attributes, or updates the caller’s internal reference.
ChilkatPath return content * Return command that returns the current node’s content.
ChilkatPath return attribute (AttrName) Return command that returns the value of the named attribute.
ChilkatPath update reference $ Return command that updates the caller to reference the node reached by the path.
Not XPath: ChilkatPath is not related to the XPath standard. It is Chilkat’s own vertical-bar-delimited navigation and return-command syntax.

Reading Content and Attributes

Need Methods Notes
Current node content Content, ContentInt Gets direct text content of the current node.
Child content by tag path GetChildContent, GetChildContentSb, GetChildIntValue, GetChildBoolValue Reads descendant child content using a tag or tag path.
Child content by index GetChildContentByIndex Reads content of the Nth direct child.
Any descendant content by tag TagContent Returns content of the first node in the subtree having the given tag.
Attribute by name GetAttrValue, GetAttrValueInt Finds and returns the named attribute from the current node.
Attribute by index GetAttributeName, GetAttributeValue, GetAttributeValueInt Enumerates attributes using zero-based indexing.
Child attribute value GetChildAttrValue Returns content of a descendant child having a specified attribute.

Creating and Updating XML

Task Methods Behavior
Create a new child NewChild, NewChild2, NewChildInt2 Creates a new child node. Tag paths can auto-create intermediate nodes.
Create child before or after index NewChildBefore, NewChildAfter Inserts a new child before or after a direct child index.
Find or create child FindOrAddNewChild Returns an existing child at the tag path or creates it if missing.
Update child content UpdateChildContent, UpdateChildContentInt, UpdateAt Replaces content and can create missing nodes when supported by the method.
Append or add to content AppendToContent, AddToContent, AddToChildContent Appends text or increments integer content.
Update attributes UpdateAttribute, UpdateAttributeInt, UpdateAttrAt, AddOrUpdateAttribute Adds attributes when missing or updates existing values.
Add attributes AddAttribute, AddAttributeInt Adds string or integer attributes to the current node.
Increment attribute value AddToAttribute Adds an integer amount to an integer attribute value, creating it if needed.

Removing, Extracting, and Moving Subtrees

Task Methods Notes
Remove all content from current node Clear Removes children, attributes, and content, and resets the tag to unnamed.
Remove attributes RemoveAttribute, RemoveAllAttributes Removes one named attribute or all attributes from the current node.
Remove children RemoveChild, RemoveChildByIndex, RemoveChildWithContent, RemoveAllChildren Removes children by tag path, index, content, or all direct children.
Extract child subtree ExtractChildByIndex, ExtractChildByName Removes a child and returns it as an Xml subtree.
Detach current subtree RemoveFromTree Removes the current node and its subtree from the document, making it the root of its own tree.
Add or insert existing subtree AddChildTree, InsertChildTreeBefore, InsertChildTreeAfter Adds or moves a subtree as a child. If the subtree belonged to another XML document, it is effectively transferred.

Searching and Matching

Search / Match Need Methods Behavior
Check current node content ContentMatches Matches current node content against a wildcard pattern.
Check child content ChildContentMatches Matches content at a child tag path against a wildcard pattern.
Find by tag SearchForTag, SearchForTag2 Breadth-first search over the subtree rooted at the caller.
Find by content SearchForContent, SearchForContent2, SearchAllForContent, SearchAllForContent2 Finds nodes whose content matches a wildcard pattern.
Find by attribute SearchForAttribute, SearchForAttribute2 Finds a node with a given tag and attribute value pattern.
Find record-style nodes FindNextRecord Iterates over high-level records where a child at a tag path matches a content pattern.
Existence checks HasChildWithTag, HasChildWithContent, HasChildWithTagAndContent, HasAttribute, HasAttrWithValue Quick checks for child nodes or attributes.
Iterating search results: Search methods that accept afterPtr can be called repeatedly. Pass the previously returned node as afterPtr to continue searching after that point.

Sorting and Reordering

Sort / Reorder Task Method Sort Basis
Sort direct children by tag SortByTag Child tag name.
Sort direct children by content SortByContent Child content as text.
Sort direct children by attribute SortByAttribute, SortByAttributeInt Attribute value as text or integer.
Sort record nodes by grandchild content SortRecordsByContent, SortRecordsByContentInt Content of a child/grandchild identified by tag.
Sort record nodes by grandchild attribute SortRecordsByAttribute Attribute value in a grandchild node.
Case-insensitive sorting SortCaseInsensitive If true, all sort methods use case-insensitive comparisons.
Swap nodes SwapNode, SwapTree Swaps tag/content/attributes only, or swaps entire subtrees.

Binary, Encoded, Compressed, and Encrypted Content

Need Methods / Properties Behavior
Store binary content SetBinaryContent, SetBinaryContentBd, SetBinaryContentFromFile Stores binary data as base64 in XML, optionally Zip-compressed and/or AES-encrypted first.
Read binary content GetBinaryContent, SaveBinaryContent Restores binary content, optionally unzipping and/or decrypting according to flags.
Zip only current content ZipContent, UnzipContent Compresses or decompresses the current node content.
Zip entire subtree ZipTree, UnzipTree Compresses the node’s content and entire subtree into base64 Zip data and later restores it.
Encrypt or decrypt content EncryptContent, DecryptContent Uses 128-bit CBC AES encryption. Encrypted content is stored as base64.
Detect base64-like content IsBase64 Returns true if node content contains only base64-allowed characters, ignoring whitespace.
B/Q encode content BEncodeContent, QEncodeContent, DecodeContent Encodes multibyte text bytes into MIME-style B or Q encoded words and decodes them later.

Cleaning, Pruning, and Utility Operations

Task Method Purpose
Scrub XML text Scrub Recursively applies cleanup directives such as trimming attribute/content whitespace, lowercasing tags or attributes, and removing control characters.
Remove tags recursively PruneTag Removes all occurrences of a tag and its descendants from the subtree. Returns the number removed.
Remove attributes recursively PruneAttribute Removes all occurrences of an attribute from the subtree. Returns the number removed.
Accumulate content AccumulateTagContent Combines content from all nodes having a tag, while optionally skipping subtrees rooted at selected tags.
Decode entities DecodeEntities Utility method to decode HTML entities in a string.
Stylesheet declarations AddStyleSheet, RemoveStyleSheet Adds or removes XML stylesheet declarations.
Copy or swap node content Copy, SwapNode, SwapTree Copies or swaps node data, either shallow node data or complete tree data.

Tag and Namespace Checks

Need Method / Property Example Use
Check full tag TagEquals Compare against the complete tag, including prefix.
Check namespace prefix TagNsEquals Compare only the namespace prefix portion of the tag.
Check unprefixed tag TagUnpEquals Compare only the tag name without namespace prefix.
Get unprefixed tag TagUnprefixed For soapenv:Body, returns Body.
Get namespace prefix TagNsPrefix For soapenv:Body, returns soapenv.
Find tag index in path TagIndex Returns the index of a node with the given tag at the specified tag path, or -1 if not found.

Diagnostics and Troubleshooting

Problem Area Member What to Check
Load, parse, save, or method failure LastErrorText Provides detailed information about the last method or property access. Check it after failures or unexpected behavior.
Node reference moved unexpectedly *2 methods, CopyRef, GetSelf Remember that many methods ending in 2 update the caller’s internal reference.
Path does not find a node FindChild, HasChildWithTag, ChilkatPath Confirm tag-path delimiter usage, namespace prefixes, and index placeholders.
Wrong namespace match Tag, TagNsPrefix, TagUnprefixed Decide whether code should compare full tag names or unprefixed tag names.
Unexpected output formatting EmitCompact, EmitXmlDecl, EmitBom, Encoding Check compact output, XML declaration, BOM, and declared encoding settings.
Binary content cannot be restored GetBinaryContent, SaveBinaryContent, unzipFlag, decryptFlag Use flags matching the options used when binary content was stored.

Common Pitfalls

Pitfall Better Approach
Assuming Content includes child-node text. Content is only the text directly contained by the node. Use child traversal or accumulation methods to gather descendant text.
Using ChilkatPath as if it were XPath. Use Chilkat’s documented command syntax. It is not the XPath standard.
Forgetting that *2 methods move the caller’s reference. Use non-2 methods when a separate returned object is safer, or use GetSelf / CopyRef deliberately.
Comparing namespace-prefixed tags using only local names. Use TagUnprefixed or TagUnpEquals when the namespace prefix should be ignored.
Expecting Encoding to convert bytes. Encoding changes the declaration value; it does not convert the document content to another encoding.
Removing a subtree without realizing it becomes its own tree. RemoveFromTree detaches the current node and makes it the root of a separate tree.

Best Practices

Recommendation Reason
Use tag paths for concise access to nested children. Methods such as GetChildContent, UpdateChildContent, and FindChild can work with tagA|tagB|tagC paths.
Use FindOrAddNewChild when duplicate children should be avoided. NewChild always creates a new child even if one already exists.
Use UpdateAt and UpdateAttrAt when auto-creating paths is desired. These methods can create nodes along the path when autoCreate is true.
Use namespace-aware tag helpers when working with SOAP or namespaced XML. TagNsPrefix, TagUnprefixed, TagNsEquals, and TagUnpEquals simplify comparisons.
Check NumChildren and NumAttributes before indexed access. Indexed child and attribute methods are zero-based.
Use GetRoot or GetRoot2 before emitting a full document. GetXml includes the XML declaration only when called from the document root.
Use Scrub for broad cleanup before comparison or output. It can normalize whitespace, lower-case tags or attributes, and remove control characters across the subtree.
Check LastErrorText after failures. It provides the most useful diagnostic detail for loading, path navigation, updating, binary content, compression, encryption, and saving.

Summary

Chilkat.Xml is the primary Chilkat class for in-memory XML tree manipulation. It supports loading and saving XML, navigating nodes, reading and writing content, managing attributes, working with namespaces, adding and removing subtrees, searching by tag/content/attribute, sorting child records, scrubbing XML, handling CDATA and XML declarations, storing binary data as base64, and optionally compressing or encrypting node content.

The most important usage distinction is between methods that return a new Xml object reference and methods ending in 2, which update the caller’s internal reference to point to a different node.