Encoding and characters
Encoding declaration
The encoding pseudo-attribute in the XML declaration, telling the parser which character encoding the file's bytes are in.
It is a description of the bytes, not a request to convert them. If the declaration and the file disagree, the parser decodes with the wrong table and fails somewhere unpredictable — usually with a syntax error that names a character rather than the encoding.
There is a bootstrapping trick behind it: the parser has to read the declaration before it knows the encoding, which works because every supported encoding renders `<?xml` recognisably enough to get that far. That is also why an unusual encoding must still be ASCII-compatible at the start of the file.
- Defined in
- XML 1.0 §4.3.3
- Category
- Encoding and characters
- Also written
- encoding=, charset declaration
Shown, not asserted
All 2 claims are executed on every test run, against the same engines the tools use. If the behaviour changes, the test fails rather than this page quietly becoming wrong.
Declaring UTF-16 over UTF-8 bytes does not convert anything — it breaks the parse.
document.xml <?xml version="1.0" encoding="UTF-16"?> <x>hi</x>What the engine returns
Blank needed here (line 1)Omitting the declaration is fine: with no byte order mark, UTF-8 is the default.
document.xml <x>café</x>What the engine returns
Well-formed.
What catches people out
- Changing the declaration does not transcode the file. Convert the bytes, then update the declaration.
- An HTTP Content-Type charset parameter outranks the document's own declaration for most consumers, which is how a correctly-encoded file still arrives mangled.
- An encoding name the parser does not know is a fatal error, not a fallback to UTF-8.
Where it bites
A definition on its own is trivia. These are the pages where this term decides whether a document works.
- Parse errorsUnsupported encodingWhat an unknown encoding name reports.
- Parse errorsBlank needed hereThe message above, and what it usually really means.
- ToolsXML validatorReports the encoding it detected alongside the verdict.
Related terms
- XML declarationThe optional <?xml version="1.0" encoding="UTF-8"?> at the very start of a document, declaring its version and character encoding.
- UTF-8The default encoding for XML, and the one every conforming parser must support along with UTF-16.
- Byte order markThe optional U+FEFF character at the start of a file, marking the encoding and — in UTF-16 — its byte order.
- Invalid XML characterA code point XML forbids in a document at all — most of the C0 control range — which cannot be included literally or as an escape.
Get started
Bring order to the XML your team can't afford to ignore.
Create a free account and get a private workspace to search, validate, diff, and monitor your XML feeds, sitemaps, schemas, and vendor integrations.