Safely Decoding HTML Character References in API and Scraper Pipelines
XML feeds, CMS exports, email templates, and legacy SOAP APIs routinely return text containing named HTML entities (&, ", ), decimal references ('), or hexadecimal references (’). Unlike HTML5, strict XML 1.0 only predefines five named entities (&, <, >, ", '), which is why JSON/XML serializers often emit numeric codes instead of or —.
Decoding untrusted HTML by injecting it into a live DOM element's innerHTML can trigger event handlers like <img onerror=...> or fetch external images. Using an inert document parser or pure character-reference decoder guarantees zero network fetches and zero script execution while preserving non-breaking spaces and astral-plane Unicode.
- Supported SyntaxesHTML5 named references (&, —), decimal (—), and hexadecimal (— / —).
- Security ModelParses character references into inert text nodes (DOMParser / lookup table) — zero script execution.
- Double-Escape DetectionHighlights double-encoded artifacts like &lt; or &quot; common in RSS and CMS exports.
Why does ' fail in older HTML4 parsers while ' works everywhere?
XML 1.0 and HTML5 define ' for the single quote, but HTML4 did not. Decimal ' and hex ' work identically across HTML4, HTML5, and XML.
How do I fix double-encoded text like &quot;?
Double-encoding occurs when already-escaped HTML is passed through an escaper a second time. Running the decoder twice restores the original character while confirming the bug in your serialization layer.
What is the difference between a regular space and ?
A regular space is U+0020, whereas decodes to U+00A0 (NO-BREAK SPACE), which prevents line wrapping and can break strict string equality checks in tests.