Escape and unescape XML text

Escaping depends on where the text goes. Pick the context; unescaping decodes once and never turns data into markup on this page.

Direction

Contexts

Element text needs & and < escaped (and > so that “]]>” can never appear). Attribute values also need the surrounding quote escaped, and tabs and line breaks written as character references, because XML normalises literal ones to spaces. CDATA cannot contain “]]>”, so it is split across two sections.

Unescaping decodes &amp;, &lt;, &gt;, &quot;, &apos; and numeric references exactly once: &amp;lt; becomes &lt;, not “<”. Unknown names such as &nbsp; (an HTML entity, not an XML one) are left as written and listed.

Questions

Why is &nbsp; not decoded?

XML predefines only five entities. &nbsp; exists in HTML or in a DTD; without that declaration it is an error in XML. Use &#160; instead.

Is the unescaped result shown as HTML?

No. Output is always plain text in a text box, so decoded markup is never interpreted by the page.