I have a basic understanding of XML. My question is why is it necessary to mention the encoding used at the beginning of a XML document and why encoding is required ?
2 Answers
It is not required, although usually you may want to include it:
In the absence of external character encoding information (such as MIME headers), parsed entities which are stored in an encoding other than UTF-8 or UTF-16 must begin with a text declaration (see 4.3.1 The Text Declaration) containing an encoding declaration.
So, for example, when transferring XML via HTTP, XML parser might use the value from Content-Type
header like this:
Content-Type application/xml; charset=UTF-8
But once this document is stored locally, it would not contain this information - thus it seems like a good idea to include encoding into the declaration part of XML document.

- 34,606
- 6
- 81
- 98
-
Unlike the `VersionInfo`, the `EncodingDecl` in the BNF grammar notation does [NOT look optional](https://www.w3.org/TR/REC-xml/#sec-TextDecl). – K3---rnc Feb 19 '17 at 16:31
why is it necessary to mention the encoding used at the beginning of a XML document
It isn't. There are defaults. (UTF-8 and UTF-16, which can be reliably distinguished between programatically)
and why encoding is required
Computers only understand binary. Encoding is the process of representing letters, numbers, etc in binary so it can be processed by a computer. Different encodings store the characters in different ways.

- 914,110
- 126
- 1,211
- 1,335
-
-
-
1@Quentin, is that true? From the spec: `TextDecl ::= '' - I think EncodingDecl can me ommited only if the whole XML delcaration is being ommited. – kamituel Mar 12 '13 at 17:39
-
-
-
@kamituel — Those question marks mean "zero or one". So you can omit VersionInfo and/or EncodingDecl – Quentin Mar 12 '13 at 17:40
-
-
@kamituel — Ah, good point. Nothing wrong with omitting the entire declaration though. – Quentin Mar 12 '13 at 17:42
-
@Quentin When an XML declaration can be omitted than is there a need to use it ? I think the parser would thrown some error if an XML declaration is missing..not sure though... – AmritaS Mar 12 '13 at 17:47
-
@AmritaS - you need to use declaration if you need to specify encoding (which is usually a good practice). Otherwise it can be ommited. – kamituel Mar 12 '13 at 18:01