为什么 XML 文档必须有一个根元素?

Why must XML documents have a single root element?

决定在 XML 文档中使用单个根元素的动机是什么?

有人可以解释为什么 XML 设计团队做出这个决定吗?

XML specification 中所述:

Definition: There is exactly one element, called the root, or document element, no part of which appears in the content of any other element. [...] The elements, delimited by start- and end-tags, nest properly within each other.

根据 Wikipedia definition of XML

Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. The W3C's XML 1.0 Specification and several other related specifications—all of them free open standards—define XML.

基本上XML是一组规则,以确保每个文档都具有相同的标准。如果你有几个小时的时间可以打发并且想无聊死了,你可以阅读 the specification here


回到您的问题,文档中只有一个根元素是一项设计决定

其中一个主要优点是允许构建 tree structure。解析具有预定义结构的逻辑树比解析浮动的不同类型节点的集合更容易。

有了预定义的结构,也可以更轻松地遍历文档并找到您要查找的信息。

您问的是设计动机问题,如果不只是推测,通常很难回答 after-the-fact。

幸运的是,Tim Bray 捕捉并记录了一些 design history and motivations behind XML, and says this regarding exactly one element, called the root, or document element:

Roots and Nests

This paragraph (which, strictly speaking is unnecessary - it is merely amplifying the consequences of the grammar) describes the essence of well-formedness. Simply stated, there has to be one element that contains everything else, and all the elements have to nest nicely within each other - no overlapping! All this "root" and "nest" terminology suggests trees, which is just fine.

The fact that XML requires a single root element is more important than you might think; given that we expect to be transmitting these documents over network links which, we all know, are sometimes slow, flaky, and unreliable, it's a really good idea if the beginning and (especially) the end of every document is clearly marked, so that even if the guy on the other end is slow in closing down the link, you know when you've got the whole message.

另请参阅: