Web & Encoding
XML Encoding Explained: UTF-8, UTF-16, and the XML Declaration
An XML encoding declaration describes how the document's bytes represent characters. It must agree with the bytes and with any authoritative transport metadata.
Published
The XML declaration and encoding name
When present, the XML declaration belongs at the beginning of the document. Its encoding value names the actual character encoding of the document entity; it does not convert bytes by itself.
<?xml version="1.0" encoding="UTF-8"?>
<message>Ready</message>UTF-8 vs UTF-16
| Encoding | Useful characteristics | XML requirement |
|---|---|---|
| UTF-8 | ASCII-compatible and usually compact for Latin-heavy text | Every conforming XML processor must accept it |
| UTF-16 | Uses 16-bit code units and may be identified by byte order | Every conforming XML processor must accept it |
What happens when encoding is omitted
Without authoritative external encoding information, a document that has neither a byte-order mark nor an encoding declaration must use UTF-8. Ordinary ASCII-only content is also valid UTF-8.
A transport protocol such as HTTP can supply external encoding information, so diagnose the bytes, declaration and transport metadata together.
Byte Order Mark and UTF-16 detection
A UTF-16 XML entity must begin with a byte-order mark when no higher-level mechanism determines byte order. UTF-8 may use a BOM, but it is not required.
The BOM is an encoding signature, not document text.
Why an encoding mismatch fails
Declared: UTF-8
Actual bytes: Windows-1251
Result: decoding error or corrupted text- Save the file in the encoding named by the declaration.
- Send compatible HTTP Content-Type metadata.
- Decode uploaded bytes before passing text to a browser-based converter.
- Do not fix mojibake by replacing characters after a lossy decode.
Try the example
Parse a declared UTF-8 document
A Unicode value remains intact after the XML text has been decoded correctly.
<?xml version="1.0" encoding="UTF-8"?><message>Привет, €</message>Expected result: The JSON output preserves the Cyrillic text and euro sign.
Check the parsed document
Convert XML after confirming its encoding
Decode the file correctly, then paste the resulting XML text and inspect its JSON mapping locally.