Cheatsheet: XML
Last updated 2026-09-21
Document basics
An XML declaration identifies the XML version and character encoding.
Every well-formed XML document has exactly one root element.
Elements start with an opening tag and end with a matching closing tag.
Empty elements can use a self-closing tag.
XML is case-sensitive, so opening and closing tag names must match exactly.
Attributes and namespaces
Attributes provide additional data on an element and must be quoted.
Use attributes for metadata and elements for repeatable structured content.
A default namespace applies to unprefixed elements in its scope.
Prefixed namespaces distinguish elements from different vocabularies.
Namespace declarations can appear on the root and be used by descendants.
Text, escaping, and markup
Escape reserved characters in text and attribute values with predefined entities.
CDATA sections contain text that should not be parsed as markup.
Comments add notes and are ignored by XML parsers.
Processing instructions pass application-specific instructions.
Mixed content allows text and child elements together.
Use nesting to represent hierarchical data.
Document type declarations can define or reference a DTD.
Well-formed vs valid, and schema validation
Well-formed = follows XML's syntax rules (one root, matched/self-closed tags, quoted attributes). It doesn't require a schema.
Valid = well-formed AND conforms to a DTD or XML Schema that constrains allowed elements/attributes.
Validate against a DTD from the command line.
Validate against an XML Schema (XSD) from the command line.
Querying with XPath
Select every <title> element anywhere in the document.
Select <title> only when it's a direct child of <book>.
Select elements by matching an attribute value.
Select elements by matching a different attribute's value.
Run an XPath query from the command line with xmllint.