Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

Are multiple XML declarations in a document well-formed XML?

Is having two XML declarations in the same document well-formed XML?

<?xml version="1.0" encoding="UTF-8"?>
<a>
 <?xml version="1.0" encoding="UTF-8"?>
 <b>
  hello
 </b>
</a>

I believe it is not, however I can't find a source to back me up on this.

From Extensible Markup Language (XML) 1.0

Definition: XML documents SHOULD begin with an XML declaration which specifies the version of XML being used.

The pesky word "should" is there. It says ideally the document starts with an XML declaration. It says nothing about having another one within the document.

The document type declaration MUST appear before the first element in the document.

This is close, but it doesn't talk about the XML declaration itself, even though it should come before it.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Only one XML declaration is permitted in well-formed XML, and it must be at the top if anywhere.

Must be at the top

See the definition of document in the Well-Formed XML Documents section of the XML Recommendation:

[1]     document ::= prolog element Misc*

Then check prolog:

[22]    prolog   ::= XMLDecl? Misc* (doctypedecl Misc*)?

And then XMLDecl:

[23]    XMLDecl  ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'

So, we see that the EBNF permits an XML declaration at the top of the document.

Only one

Processing instructions...

[16]    PI       ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
[17]    PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))

...in general may occur elsewhere, but a second XML declaration is precluded by virtue of the definition of PITarget and this statement:

The target names " XML ", " xml ", and so on are reserved for standardization in this or future versions of this specification.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...