Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must a new line follow the XML declaration?

Tags:

xml

Is this one a valid XML instance? It has nothing between the the XML declaration and the root node.

<?xml version="1.0" encoding="UTF-8"?><data></data>

I could not find the right place in the XML specification myself and hope that somebody will help me...

like image 553
Andrej Avatar asked Dec 05 '11 11:12

Andrej


People also ask

Does new line matter in XML?

XML doesn't require "lines", it's a nested storage structure and any additional newlines and whitespace will be ignored, and they just take up additional storage space.

Is it mandatory to start with some lines that describe the XML version?

XML declaration contains details that prepare an XML processor to parse the XML document. It is optional, but when used, it must appear in the first line of the XML document.

What should be the first line of XML document?

The first line of an XML document should be a declaration that this is an XML document, including the version of XML being used.


2 Answers

The spec (see 2.8 Prolog and Document Type Declaration) does not require (but does allow) a newline to follow the XML Declaration.

Formally this is written as:

[16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
...
[22] prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?
[23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
...
[27] Misc ::= Comment | PI | S

As you can see in [22] prolog the XML Declaration is optional (see the questionark after the symbol) and zero, one or more (see the star) Misc can follow which are: Comments, other Processing Instructions (PI) or Whitespace (S). Whitespace includes the newline.

Because Misc is optional here, there can but need not follow a newline after the declaration.

like image 141
Michael Krelin - hacker Avatar answered Oct 23 '22 06:10

Michael Krelin - hacker


New lines or so are not part of the spec. When you, for example, write a XML Document with the XMLOutputter Class (in Java), you get a file without newlines. Newlines are for humans.

like image 2
Thargor Avatar answered Oct 23 '22 07:10

Thargor