32

Is it OK to put comments before the XML declaration in an XML file?

<!--
Is this bad to do?
-->
<?xml version="1.0" encoding="utf-8"?>
<someElement />
sourcenouveau
  • 29,356
  • 35
  • 146
  • 243
  • 3
    When you tried it, what happened? – S.Lott Jul 28 '09 at 20:24
  • 3
    Hey! Don't call me out on my bad habit of asking first and experimenting later... ^_^ – sourcenouveau Jul 28 '09 at 21:44
  • 5
    Experimenting would only allow you to say "well, it works on *my* computer", which isn't that helpful. Some XML processors may allow it, some may not. But if you follow the spec, then there's a greater chance that ALL XML processors (present and future) will be able to process your files. – Gary McGill Jul 28 '09 at 21:54
  • 1
    anyway, guess it's clear that this is not allowed - for reason whysoever :D and if your parser marks this as correct (which isn't good but possible), experimenting doesn't really help anyway.... – Atmocreations Jul 28 '09 at 21:55

4 Answers4

53

No, it's not OK.

Appendix F of the XML spec says:

Because each XML entity not accompanied by external encoding information and not in UTF-8 or UTF-16 encoding must begin with an XML encoding declaration, in which the first characters must be '< ?xml', any conforming processor can detect, after two to four octets of input, which of the following cases apply.

Ah, but, section F is non-normative, you say.

Well, section 2.1 gives the production for a well-formed XML document, thus:

[1]     document       ::=       prolog element Misc*

...and in section 2.8 we get the production for "prolog":

[22]    prolog     ::=       XMLDecl? Misc* (doctypedecl Misc*)?
[23]    XMLDecl    ::=      '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'

So, you can omit the < ?xml declaration, but you can't prefix it with anything.

(Incidentally, "Misc" is the category that comments fall into).

Gary McGill
  • 26,400
  • 25
  • 118
  • 202
7

according to this page, this is illegal:

When adding reference comments to your XML code, remember that they cannot come at the very top of your document. In XML, only the XML declaration can come first:

<?xml version="1.0"?>
Ricky Sixx
  • 581
  • 1
  • 10
  • 25
Atmocreations
  • 9,923
  • 15
  • 67
  • 102
5

The XML declaration specifies the document encoding, which is as important for comments as for structural XML. Therefore, the declaration should go first. I wouldn't be surprised if many XML readers were able to deal with this, but it's a bad idea.

jlew
  • 10,491
  • 1
  • 35
  • 58
  • 1
    well, i agree with you. in fact the parser must have an idea how to read the document as he wouldn't be able to read the encoding neither. therefore only putting multi-byte characters into this comment should be disallowed... – Atmocreations Jul 28 '09 at 20:21
1

No, this does not comply with XML standards, but comments are good.