XML Special Character Escaping: What Changes, What Stays the Same, and When to Use It

A practical review of XML character escaping: the five predefined entities, numeric character references, apostrophe and quote rules, CDATA, and copy/paste limits.

XML escaping replaces characters that have structural meaning in markup with references the parser decodes back into the original characters. This review covers whether escaping fits your use, what it changes, and where escaped text causes problems once it leaves an XML parser. It draws on the XML 1.0 rules and general serializer behavior. No tool-specific tests or measurements were available, so claims about particular editors, platforms or assistive technologies are flagged as unverified.

Is XML escaping suitable for your intended use?

Escaping is necessary whenever arbitrary text goes into an XML document, such as a configuration file, a feed, a SOAP or other XML payload, an SVG file, or a string resource. Its main benefit is that the text survives parsing unchanged. A reader that decodes the document gets exactly the characters you started with, and stray symbols in the data cannot break the document or inject markup.

The main tradeoff is that the escaped form is only correct inside an XML parsing context. Outside one, it is clutter that people misread and that systems may escape a second time. Keep data unescaped in storage and escape it once, at the moment you write XML, preferably through a serializer or XML library rather than hand-written replacements.

Plain text is the better choice when the destination is not XML. Examples include plain-text email, logs, JSON values, spreadsheet cells, database fields, and user-facing labels that a program displays directly. Escaping text for these destinations adds visible entity codes without any benefit.

What escaping actually changes

XML escaping is a change to the serialized characters, not a visual effect. It is unrelated to reversed or mirrored text, Unicode "font" substitution, CSS styling or bidirectional display. A literal ampersand in the source becomes the five characters & in the file. A conforming parser turns those five characters back into one ampersand. The text a program reads after parsing is identical to the original. Only the on-disk or on-the-wire form differs.

Two mechanisms exist. Predefined entity references are named shortcuts, and XML 1.0 defines exactly five of them. Numeric character references name a Unicode code point in decimal (&#NNNN;) or hexadecimal (&#xHHHH;) and can represent any character the document is allowed to contain.

XML escape character list

Character | Entity reference | Decimal reference | Hex reference | Must be escaped when
< (less-than) | < | < | < | Always, in text and attribute values
& (ampersand) | & | & | & | Always, in text and attribute values
(greater-than) | > | > | > | Only in the sequence ]]> in text; escaping it everywhere is allowed and common
" (double quote) | " | " | " | Inside an attribute value delimited by double quotes
' (apostrophe) | ' | ' | ' | Inside an attribute value delimited by single quotes

These five are the only named entities an XML parser recognizes without a DTD. HTML names such as  , © or — are not predefined in XML. Using them in a document that does not declare them is a well-formedness error. Use the numeric form instead, for example   for a non-breaking space.

Escaping the apostrophe and quotes

Apostrophes and double quotes never need escaping in element content. In attribute values, only the character that delimits the value must be escaped, so title="Jerry's" is valid as written while title='Jerry's' needs the reference. Many serializers escape both quote characters in attributes regardless, which is harmless.

If the same string may also be read by older HTML processors, prefer ' over '. HTML 4 did not define ', although HTML5 does. The numeric form works in both.

Worked example

The input below contains an ampersand, angle brackets, double quotes and an apostrophe. Placed as element content, it needs only the ampersand and the less-than sign escaped. The greater-than escape shown is optional.

Input text:
Tom & Jerry's "<b>" tag

As element content:
<note>Tom &amp; Jerry's "&lt;b&gt;" tag</note>

As a double-quoted attribute value:
<note text="Tom &amp; Jerry's &quot;&lt;b&gt;&quot; tag"/>

Parsing either line returns the original string exactly. In the attribute form, the apostrophe stays literal because the value is delimited by double quotes.

Common mistakes in hand-written escaping

  • Wrong replacement order: if you replace < with < and then replace & with &, the result is &lt;. Replace & first, or use a library.
  • Double escaping: escaping text that is already escaped turns & into &amp;, and readers then see the literal entity text.
  • Assuming a library escapes quotes: some helpers do not escape quote characters by default. For example, Python's xml.sax.saxutils.escape handles &, < and > only, and quoteattr is the separate function intended for attribute values.
  • Splitting emoji into surrogates: characters outside the Basic Multilingual Plane take one reference to the full code point, such as 😀. References to surrogate halves such as � are illegal in XML.
  • Trying to escape forbidden characters: in XML 1.0, most C0 control characters other than tab, line feed and carriage return are not allowed at all, even as numeric references. They must be removed, replaced, or encoded some other way, such as Base64. XML 1.1 permits references to them, except NUL, but parser support for 1.1 varies.
# Python standard library
from xml.sax.saxutils import escape, quoteattr

escape('Tom & Jerry <b>')       # 'Tom &amp; Jerry &lt;b&gt;'
quoteattr('say "hi"')           # adds delimiting quotes and escapes as needed

CDATA sections as an alternative

A CDATA section (<![CDATA[ ... ]]>) lets you place < and & in element content without escaping them, which keeps embedded code or markup readable in the raw file. It cannot appear in attribute values. It cannot contain the sequence ]]>, which must be split across two sections. It also does nothing for characters XML forbids. A serializer may use escaping or CDATA interchangeably, because the parsed text is the same.

Whitespace and line endings

Parsers normalize literal tabs, line feeds and carriage returns inside attribute values to spaces, and they convert CR LF line endings to LF everywhere. If an attribute must keep a newline or tab, write it as
, or . This is one of the few cases where escaping changes what the parser returns. Without the reference, the original whitespace is lost.

Readability and usability after copying or sharing

Escaped text is only readable as intended after an XML parser or XML-aware viewer decodes it. If you copy it from a raw file into a chat message, a ticket or a plain-text field, the recipient sees &, < and similar codes literally. Pasting it back into an XML tool that escapes on input produces double escaping. Copy the decoded value when sharing text with people, and copy the raw form only between XML sources.

Search and editing are affected in the same way. Searching the raw file for "R&D" will not match R&D, and editing escaped text by hand makes it easy to leave a bare ampersand behind, which breaks well-formedness. XML-aware editors and query tools that operate on parsed content avoid these problems. Plain text search over the raw file does not.

For accessibility, the general principle is that assistive technology works with whatever text the displaying application presents. When an application parses the XML and shows the decoded content, escaping should not affect what is announced. When raw escaped source is shown, entity codes are part of the visible text and may be read aloud as symbols and letters. No testing of specific screen readers or destinations was available for this review, so verify in the actual environment if accessibility matters for your output. When people will read the content directly rather than through an XML consumer, provide a plain-text equivalent.

Bottom line

XML escaping is a lossless, reversible encoding for markup contexts. Always escape < and &. Escape the delimiting quote inside attributes. Use numeric references for anything beyond the five predefined entities. Let a serializer do the work, escape once at output time, and hand people the decoded text whenever the destination is not XML.