# Escape XML characters without double-encoding data

Source: https://xsdhub.com/learn/xml-escape-characters

Fix unescaped ampersands and less-than signs, choose attribute quotes correctly, and understand when CDATA helps. Includes valid and invalid XML examples.

## Why a normal sentence can break XML

A customer name such as Pine & Paper contains an ampersand that the XML parser treats as the start of a reference. In element text, write Pine &amp; Paper. Likewise, use &lt; for a literal less-than sign. The parser returns the original characters to the application; escaped markup is a representation of the text, not a change to the customer name.

## Element text and attributes

In text content, a quote normally needs no special treatment. Inside an attribute, escape whichever quote character delimits the value, or choose the other delimiter. This example represents a company name containing an ampersand and a message containing double quotes.

```xml
<company name="Pine &amp; Paper">
  <message>Say "hello" when 2 &lt; 3.</message>
  <label text="Say &quot;hello&quot;"/>
</company>
```

## The five predefined references

Use &amp; for &, &lt; for <, &gt; for >, &quot; for a double quote and &apos; for an apostrophe when the context calls for them. A plain > is usually allowed in text, but the sequence ]]> cannot appear there as ordinary character data. Numeric references such as &#38; represent characters too. HTML-only names such as &nbsp; are not automatically available in XML; use a literal non-breaking space or &#160; instead.

## When CDATA is useful

CDATA can make a block of text containing markup-like characters easier to read. It belongs in element content, not inside an attribute. References inside CDATA are literal text rather than decoded entities, and the closing sequence ]]> cannot occur inside a single CDATA block. CDATA blocks cannot nest.

```xml
<snippet><![CDATA[if (a < b && ready) { run(); }]]></snippet>
```

## Avoid escaping twice

If your source value is already the character &, pass that value to an XML serializer and let it escape once. Manually converting it to &amp; before serialization can produce &amp;amp;. After parsing, that double-escaped document contains the visible text &amp; instead of the intended ampersand. Decide whether an input is raw data or serialized XML before applying replacements.

## Validate the serialized result

Paste the complete output into the XML syntax validator. Fix the earliest reference or quoting error, then check again. Formatting makes the structure easier to read but does not recover the intended data from a broken escape. XSDHub does not allow custom entity declarations or DTDs, so use predefined references, numeric references or normal Unicode text.

## Primary references

- [W3C XML syntax and character references](https://www.w3.org/TR/xml/)
