What Is XML?
XML (Extensible Markup Language) is a text format for storing and exchanging structured data. It describes what each value means by surrounding it with named elements. XML does not come with a fixed vocabulary, so a team or standard can define tags such as <device>, <alert>, or <invoice> for its own data.
XML is designed to be read by software, but its labelled structure also makes it understandable to people. It is a good fit when data needs a strict hierarchy, validation, namespaces, comments, or compatibility with an existing XML-based system. XML describes data; it does not decide how that data should look on a screen.
Read Your First XML Document
<?xml version="1.0" encoding="UTF-8"?>
<email id="msg-1" priority="high">
<from>alice@example.com</from>
<to>bob@example.com</to>
<subject>Project update</subject>
<body>Status is green & deployment is complete.</body>
</email>
Read the document from the outside inward:
- The optional XML declaration identifies the XML version and text encoding.
<email>is the single root element. Every other element belongs inside it.idandpriorityare attributes that add details about the email.<from>,<to>,<subject>, and<body>are child elements.- The ampersand in the body is written as
&because a plain&has a special meaning in XML.
Core Building Blocks
| Term | Meaning | Example |
|---|---|---|
| Declaration | An optional first line that states the XML version and character encoding. | <?xml version="1.0" encoding="UTF-8"?> |
| Tag | Markup that opens, closes, or represents an empty element. | <date> and </date> |
| Element | A start tag, its content, and a matching end tag. An element may contain text or more elements. | <date>2026-08-31</date> |
| Root element | The one outermost element that contains the document's data. | <email>...</email> |
| Attribute | Extra information written inside a start tag. Its value must be quoted. | <email priority="high"> |
| Text content | The character data stored between tags. | Project update |
| Entity reference | A safe representation of a reserved character. | <, >, &, ", ' |
| Comment | A note that is not part of the document's normal data. | <!-- Review before sending --> |
XML Forms a Tree
An XML document is a hierarchy. The root is at the top, child elements sit inside a parent, and elements at the same level are siblings. This tree structure is why XML works well for data that naturally contains groups and subgroups.
<library>
<book id="1">
<title>Network Basics</title>
</book>
<book id="2">
<title>XML Essentials</title>
</book>
</library>
Here, library is the root, the two book elements are sibling children, and each title is a child of one book. Repeating an element is the normal XML way to represent a list.
Select XML Data with XPath
XPath is a query language for selecting nodes from an XML tree. Read a basic path from left to right, one level at a time:
| XPath | What it selects in the library example |
|---|---|
/library/book | Both book elements directly under the root. |
/library/book/title | The title child of each root-level book. |
//title | Every title element found anywhere below the document root. |
//book[@id="2"] | The book element whose id attribute equals 2. |
The first slash begins at the document root, another slash moves to a direct child, // searches descendants at any depth, and square brackets add a condition. Namespace-aware documents require the XPath tool to associate prefixes with the relevant namespace names.
Rules for Well-Formed XML
Before software can process a document, it must be well-formed: it must follow XML's basic syntax rules.
- Use exactly one root element.
- Close every non-empty element and match tag names exactly. XML is case-sensitive, so
<Name>and<name>are different. - Nest elements correctly—close the most recently opened element first.
- Put quotation marks around every attribute value.
- Escape reserved characters when they are data rather than markup.
- Place the XML declaration first when one is included.
| Incorrect | Correct | Reason |
|---|---|---|
<name>Alex</Name> | <name>Alex</name> | Closing tags must match case. |
<b><i>text</b></i> | <b><i>text</i></b> | Elements must be nested, not crossed. |
<item active=yes> | <item active="yes"> | Attribute values must be quoted. |
<path>A & B</path> | <path>A & B</path> | A literal ampersand must be escaped. |
Well-formed XML follows the syntax rules. Valid XML is well-formed and also follows the additional rules in a DTD or schema.
Elements or Attributes?
Both can describe data, but they serve different purposes. Use elements for the main information, especially when it can repeat, contain child data, or grow later. Use attributes for short metadata that describes one element.
<user id="42" status="active">
<name>Alex Morgan</name>
<email>alex@example.com</email>
</user>
In this example, the identifier and status describe the user element, while the name and email are the actual content. This is a useful convention rather than an absolute rule; consistency with the system's schema matters most.
Special Characters and CDATA
XML reserves several characters for markup. Use their predefined entity references when those characters need to appear as text.
| Character | Reference | Typical reason |
|---|---|---|
< | < | Would otherwise begin a tag. |
> | > | Can be escaped for clarity or where required. |
& | & | Would otherwise begin an entity reference. |
" | " | Useful inside a double-quoted attribute. |
' | ' | Useful inside a single-quoted attribute. |
A CDATA section lets a document contain a larger block of text with characters such as < and & without escaping each one. The closing sequence ]]> cannot appear inside it.
<example><![CDATA[
if (count < 10 && enabled) {
run();
}
]]></example>
Namespaces Prevent Name Conflicts
Two XML vocabularies may use the same tag name for different things. A namespace connects a prefix to a unique identifier so software can tell those names apart.
<order xmlns:c="https://example.com/customer"
xmlns:p="https://example.com/product">
<c:name>Alex Morgan</c:name>
<p:name>Security Handbook</p:name>
</order>
The prefixes c and p are convenient labels. Their namespace names—the URI values—provide the identity; they do not need to open as web pages. A default namespace can also be declared with xmlns="..." when most elements belong to one namespace.
Validation with DTD and XSD
Validation checks more than basic syntax. It can require particular elements, control their order, restrict attributes, and sometimes enforce value types. This helps systems reject incomplete or unexpected data before using it.
Document Type Definition (DTD)
A DTD is a compact, older way to define an XML document's permitted structure. It may be included inside the document or stored in a separate .dtd file.
<!DOCTYPE email [
<!ELEMENT email (from, to+, subject, body)>
<!ATTLIST email id ID #REQUIRED>
<!ELEMENT from (#PCDATA)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT subject (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
In this declaration, to+ means one or more to elements, and the id attribute is required. An external DTD is referenced like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE email SYSTEM "email.dtd">
XML Schema (XSD)
XSD is written in XML and can express richer constraints, including data types such as strings, integers, dates, and booleans. It is usually preferred when an integration needs precise validation, reusable types, and namespace support.
<xs:element name="age" type="xs:positiveInteger" />
<xs:element name="joined" type="xs:date" />
A schema does not replace safe application checks. It verifies the document's declared shape, while the application must still decide whether the values are sensible and authorised.
How Programs Read XML
| Approach | How it works | Best suited for |
|---|---|---|
| Tree-based (DOM) | Loads the document into memory as a tree that code can navigate and edit. | Small or medium documents where convenient random access matters. |
| Streaming (SAX, StAX, or pull parsers) | Reads the document piece by piece instead of retaining the whole tree. | Large files, event feeds, or memory-sensitive processing. |
The exact API depends on the programming language, but the decision is similar: tree-based parsing is easier to navigate, while streaming uses less memory and can begin processing sooner.
XML Compared with JSON
| XML | JSON |
|---|---|
| Uses elements, attributes, and namespaces. | Uses objects, arrays, keys, and values. |
| Supports comments, mixed text and elements, and mature schema systems. | Usually shorter and maps naturally to common programming-language data structures. |
| Common in document formats, SOAP, configuration, and established enterprise standards. | Common in modern web APIs and application data exchange. |
Neither format is universally better. Choose the format required by the surrounding standard or system; for a new design, compare validation, interoperability, document complexity, tooling, and readability needs.
Common Mistakes to Check
- Saving the file with an encoding that disagrees with the XML declaration.
- Forgetting that element and attribute names are case-sensitive.
- Using an undeclared namespace prefix.
- Assuming whitespace is always ignored; its meaning depends on the vocabulary and application.
- Trying to parse HTML with a strict XML parser even though ordinary HTML may not be well-formed XML.
- Trusting a document only because it is well-formed or schema-valid.
Parse Untrusted XML Safely
DTDs can define custom entities, and external entities can ask a parser to load content from another file or network location. If unsafe features are enabled while processing untrusted XML, an attacker may be able to read local files, make unwanted network requests, or consume excessive resources.
Safe default: Disable DTD processing and external entity resolution when they are not required. If a trusted integration genuinely needs them, allow only the required behaviour, use maintained parser libraries, validate input size and structure, and follow that parser's security guidance.
Where XML Is Still Used
XML remains common in application and operating-system configuration, SOAP web services, SAML messages, RSS and Atom feeds, SVG graphics, document formats such as Office Open XML, build tools, and long-lived enterprise integrations. Learning the tree, namespace, and validation concepts makes these formats much easier to troubleshoot.
Quick Recap
- XML stores labelled data as one hierarchical tree.
- Well-formed documents follow XML syntax; valid documents also match a DTD or schema.
- Elements hold the main content, while attributes commonly hold concise metadata.
- Entity references and CDATA handle characters that would otherwise be treated as markup.
- Namespaces distinguish identical names from different XML vocabularies.
- XPath selects elements and other nodes by their position, name, or conditions.
- Parser settings matter: external entities should be disabled for untrusted XML unless strictly required.
