Web & Encoding
XML Escape Characters: Special Characters, Entities, and Examples
XML reserves characters that delimit markup or entity references. Escape them only where syntax requires it, using predefined entities or numeric character references.
Published
The five predefined XML entities
| Character | Entity | Typical reason |
|---|---|---|
| & | & | Starts an entity or character reference |
| < | < | Starts markup |
| > | > | Avoids the forbidden ]]> sequence in character data |
| " | " | Escapes a double-quoted attribute delimiter |
| ' | ' | Escapes a single-quoted attribute delimiter |
Escape special characters in element text
Literal ampersands and left angle brackets are not allowed in ordinary character data. A greater-than sign is normally allowed, but must be escaped when it would complete the sequence ]]>
<message>Use A & B when x < 10.</message>Escape the delimiter in an attribute value
A double quote must be escaped inside a double-quoted value, and an apostrophe must be escaped inside a single-quoted value. The other quote can appear literally.
<item label="A & B said "ready""/>
<item label='It's ready'/>Numeric character references
Both references identify the euro sign. Numeric references are useful when a character is difficult to type or must be represented explicitly, but the referenced code point still has to be legal in XML.
Decimal: €
Hexadecimal: €Common escaping mistakes
- Writing a bare & in text such as research & development.
- Escaping an already escaped entity and producing &amp;.
- Using HTML-only named entities that are not declared in XML.
- Forgetting that the attribute delimiter determines which quote must be escaped.
Try the example
Decode XML entities during conversion
The parser resolves predefined entities before JSON is generated.
<message label="A & B">x < 10 & ready</message>Expected result: The JSON values contain A & B and x < 10 & ready without entity syntax.
Validate the escaped XML
Convert an XML document with entities
Paste escaped XML and verify that the parser reads the intended characters before mapping them to JSON.