Skip to main content
XMLDir

Search 309 pages — tools, formats, elements, namespaces, directory, comparisons, XPath, datatypes, glossary, parse errors, schema errors, use cases, blog and product.

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.

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.