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:

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&amp;category=books" title="Tom &amp; Jerry" />

Escaping Other Reserved Punctuation in Attributes

  1. 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 &quot;.
    • If using single quotes (attr='...'), replace literal ' with &apos;.
  2. Angle Brackets: The less-than sign (<) is strictly prohibited inside attribute values and must always be escaped as &lt;. While the greater-than sign (>) is often tolerated, it is standard practice to escape it as &gt;.

Using Numeric Character References

As an alternative to named entities, you can use decimal or hexadecimal character references based on Unicode code points:

Both named entities (&amp;) and numeric references (&#38;) produce identical results in compliant XML parsers. Using the named entity &amp; is standard for code readability.