XML 标签缺少开始标签是否常见?

Is it common for XML tags to be missing the beginning tag?

我正在使用 python 模块 XMl ElementTree 来解析一堆 XML 文件。通常,包含文本的标签将写为,

<Tag>some text is here</Tag>

如果没有与我们将拥有的标签相关联的文本,

<Tag></Tag>

但我的一些文件只有,

<Tag/>

这在 XMLs 中常见吗?还是我正在查看构造不佳的文件?

如果没有针对结束标签的开始标签,则文档无效 Xml。没有值 <Tag /> 的标签是可以的 - 相当于 <Tag></Tag> 但没有相应的开始标签的结束标签是无效的。元素也必须正确嵌套。

常见的是

<tag/>
,相当于
<tag></tag>
,在没有内容的时候有用。 例如,您可以在 html 中看到:

<img src="foo.png"/>

但是

</tag>
单独在标准上下文中是无效的。

<tag/>这样的标签是一个空元素标签(也叫自闭合标签),对于[=12是shorthand =]:都代表一个空元素。

转自W3C Recommendation on XML:

[Definition: An element with no content is said to be empty.]
The representation of an empty element is either a start-tag immediately followed by an end-tag, or an empty-element tag.
[Definition: An empty-element tag takes a special form:]

Tags for Empty Elements

[44] EmptyElemTag ::= < Name (S Attribute)* S? />

Empty-element tags may be used for any element which has no content, whether or not it is declared using the keyword EMPTY. For interoperability, the empty-element tag SHOULD1 be used, and SHOULD only be used, for elements which are declared EMPTY.

Examples of empty elements:

<IMG align="left"
     src="http://www.w3.org/Icons/WWW/w3c_home" />
<br></br>
<br/>

关于非XML (HTML) void 元素的一句话

以上不应与HTML中的非XML概念空元素混淆, 也可以写成 <tag/>.

引自W3C HTML Language Reference(我强调了第5点):

A void element is an element whose content model never allows it to have contents under any circumstances.

start tags consist of the following parts, in exactly the following order:

  1. A < character.
  2. The element’s tag name.
  3. Optionally, one or more attributes, each of which must be preceded by one or more space characters.
  4. Optionally, one or more space characters.
  5. Optionally, a / character, which may be present only if the element is a void element.
  6. A > character.

Void elements only have a start tag; end tags must not be specified for void elements.

因此,尽管可以在非XML HTML 文档中使用<br/>,但它并不完全代表与XML 中相同的概念。它不是 self-closing 标签,而是 <br> 的语法替代,void 元素,这是一个陌生的概念XML.