SyntaxStudy
Sign Up
XML Entity References and Special Characters
XML Beginner 1 min read

Entity References and Special Characters

XML defines five predefined entity references that allow reserved characters to appear in text content and attribute values. These are: < for the less-than sign (<), > for the greater-than sign (>), & for the ampersand (&), ' for the apostrophe/single-quote ('), and " for the double-quote ("). The ampersand and less-than sign are always forbidden in text content; the others are only required in specific contexts such as inside attribute values delimited by the same quote character. Beyond the five predefined entities, XML allows documents to declare custom entities in the document's DOCTYPE declaration. A general entity maps a short name to a text string, enabling reuse of common phrases or boilerplate. Parameter entities (prefixed with %) work similarly but are used within the DTD itself. Numeric character references — A for decimal or A for hexadecimal — allow any Unicode code point to be inserted regardless of the document's encoding. Understanding the difference between parsed and unparsed entities is important in advanced DTD authoring. Parsed entities have their replacement text inserted directly into the document flow and must themselves be well-formed XML. Unparsed entities reference external binary data such as images and are associated with a NOTATION declaration. In practice, unparsed entities are rarely used in modern XML applications, having been superseded by simple URI attribute values.
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE document [
    <!-- Custom general entity declaration -->
    <!ENTITY company "Acme Corporation">
    <!ENTITY copyright "&#169; 2025 Acme Corporation. All rights reserved.">
    <!-- Numeric character reference: © = U+00A9 -->
]>
<document>

    <!-- Using the five predefined entities -->
    <rule>a &lt; b &amp;&amp; b &gt; c</rule>
    <attr value="He said &quot;hello&quot; and she replied &apos;hi&apos;"/>

    <!-- Using a custom entity -->
    <footer>&company; — &copyright;</footer>

    <!-- Numeric character references (decimal and hex) -->
    <symbols>
        Euro sign: &#8364;   <!-- decimal -->
        Heart:     &#x2665;  <!-- hexadecimal -->
        Copyright: &#xA9;    <!-- hex shorthand -->
    </symbols>

    <!-- Ampersand in attribute value must be escaped -->
    <link url="http://example.com?cat=xml&amp;page=1" />

</document>