How to Escape Ampersands in XML Attributes
In XML, reserved punctuation marks like ampersands cannot be included directly within attribute values because parsers treat them as delimiters or the start of entity declarations. To safely include these characters without causing parsing errors or invalidating the document, you must replace them with predefined XML entity references or numeric character references.
Predefined Entity References
XML provides five built-in entity references to represent reserved characters. When an XML parser encounters these references inside an attribute value, it converts them back into their literal character forms:
- Ampersand (
&):& - Double quote (
"):" - Single quote/Apostrophe (
'):' - Less-than (
<):< - Greater-than (
>):>
Escaping Ampersands
The ampersand is the character that signals the start of an entity.
If you use a literal & inside an attribute value, the
parser expects an entity name immediately following it (e.g.,
&name;). If it finds plain text or invalid syntax
instead, it throws a fatal parse error.
To include a literal ampersand, replace every instance of
& with &.
Invalid XML:
<link url="https://example.com?item=1&category=books" title="Tom & Jerry" />Valid XML:
<link url="https://example.com?item=1&category=books" title="Tom & Jerry" />Escaping Other Reserved Punctuation in Attributes
- Quotation Marks: Attribute values must be enclosed
in single or double quotes. If your value contains the same quote used
as the delimiter, you must escape it.
- If using double quotes (
attr="..."), replace literal"with". - If using single quotes (
attr='...'), replace literal'with'.
- If using double quotes (
- Angle Brackets: The less-than sign
(
<) is strictly prohibited inside attribute values and must always be escaped as<. While the greater-than sign (>) is often tolerated, it is standard practice to escape it as>.
Using Numeric Character References
As an alternative to named entities, you can use decimal or hexadecimal character references based on Unicode code points:
- Decimal ampersand:
& - Hexadecimal ampersand:
&
Both named entities (&) and numeric references
(&) produce identical results in compliant XML
parsers. Using the named entity & is standard for
code readability.