为什么我在使用 DTD 验证 XML 文件时得到 "no name for attribute"?

Why do I get "no name for attribute" when I validate my XML file with DTD?

我想设置一个参数实体,以便声明多个元素共有的属性。

我想要做的是让 "elem" 元素具有属性 "width CDATA "0”。在我完成这项工作之后,我会在更多元素上使用它。

这是我想出的代码:

<?xml version="1.0"?>
<!DOCTYPE example [
    <!ENTITY % attrs 'width   CDATA   "0"'>

    <!ELEMENT example (elem) >
    <!ELEMENT elem (#PCDATA) >
    <!ATTLIST elem %attrs; > <!-- <This errors with "no name for attribute" -->
]>

<example>
    <elem width="20">Hi how are you</elem>
</example>

我使用的代码基于对类似问题的公认答案(How do I declare attributes common to multiple elements?). However, when I run my code through XML validators (Exalt on SublimeText or xmlvalidation.com 它有误。

在上面提到的网站上,错误是:
The attribute name must be specified in the attribute-list declaration for element "elem1".

使用 Exalt,错误是:
ATTLIST: no name for Attribute at [...]

我的理解是缺少属性名称。但是我把属性名放在了参数entity上,怎么会检测不到呢?

如果我替换 %attrs;使用 'width CDATA "0"',效果很好。

为什么我会收到错误消息?

这是因为内部子集中参数实体的限制。

限制之一是不能在标记声明中使用参数实体引用。

From the spec:

Well-formedness constraint: PEs in Internal Subset

In the internal DTD subset, parameter-entity references must not occur within markup declarations; they may occur where markup declarations can occur. (This does not apply to references that occur in external parameter entities or to the external subset.)

如果您将 DTD 放在一个单独的文件中,它可以正常工作。 (您可能不需要它,但为了以防万一,see here 作为在外部文件中引用 DTD 的示例。)