Cheatsheet: XML

Last updated 2026-06-21

Document basics

An XML declaration identifies the XML version and character encoding.

<?xml version="1.0" encoding="UTF-8"?>

Every well-formed XML document has exactly one root element.

<catalog>
  <book>XML Guide</book>
</catalog>

Elements start with an opening tag and end with a matching closing tag.

<title>XML Guide</title>

Empty elements can use a self-closing tag.

<line-break />

XML is case-sensitive, so opening and closing tag names must match exactly.

<Item>Valid</Item>
<!-- <Item>Invalid</item> -->

Attributes and namespaces

Attributes provide additional data on an element and must be quoted.

<book id="b1" language="en">XML Guide</book>

Use attributes for metadata and elements for repeatable structured content.

<book id="b1">
  <title>XML Guide</title>
  <author>Ada</author>
</book>

A default namespace applies to unprefixed elements in its scope.

<feed xmlns="https://www.w3.org/2005/Atom">
  <title>Example</title>
</feed>

Prefixed namespaces distinguish elements from different vocabularies.

<xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml">Text</xhtml:div>

Namespace declarations can appear on the root and be used by descendants.

<root xmlns:svg="http://www.w3.org/2000/svg">
  <svg:svg width="100" height="100" />
</root>

Text, escaping, and markup

Escape reserved characters in text and attribute values with predefined entities.

&lt; for <
&gt; for >
&amp; for &
&quot; for "
&apos; for '

CDATA sections contain text that should not be parsed as markup.

<![CDATA[if (a < b && b > c) { return true; }]]>

Comments add notes and are ignored by XML parsers.

<!-- This is a comment -->

Processing instructions pass application-specific instructions.

<?xml-stylesheet type="text/xsl" href="style.xsl"?>

Mixed content allows text and child elements together.

<p>This is <strong>important</strong> text.</p>

Use nesting to represent hierarchical data.

<order>
  <customer id="c1">Ada</customer>
  <items>
    <item sku="A1" quantity="2" />
  </items>
</order>

Document type declarations can define or reference a DTD.

<!DOCTYPE note SYSTEM "note.dtd">

See also: