根据ID属性类型的the DTD specification:
有效性约束:ID
类型ID的值必须与名称生成匹配。一个名字绝不可以 在XML文档中出现多次作为此类型的值; 即,ID值必须唯一地标识承载它们的元素。
以下哪项解释是正确的?
换句话说,给出以下DTD声明片段:
<!ELEMENT book ANY>
<!ATTLIST book id ID>
<!ELEMENT magazine ANY>
<!ATTLIST magazine id ID>
以下XML文档代码段是否违反了有效性约束?
<book id="ID01" />
<magazine id="ID01" />
如果我将属性重命名为book-id
和magazine-id
,而不仅仅是id
,那么该如何?
答案 0 :(得分:4)
格式良好的XML文档:
<!DOCTYPE root SYSTEM "idtest.dtd">
<root>
<book id="ID01" />
<magazine id="ID01" />
</root>
DTD:
<!ELEMENT root ANY>
<!ELEMENT book ANY>
<!ATTLIST book id ID #IMPLIED>
<!ELEMENT magazine ANY>
<!ATTLIST magazine id ID #IMPLIED>
xmllint的输出:
$ xmllint --postvalid idtest.xml
<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "idtest.dtd">
<root>
<book id="ID01"/>
<magazine id="ID01"/>
</root>
idtest.xml:4: element magazine: validity error : ID ID01 already defined
<magazine id="ID01" />
^
idtest.xml:4: element magazine: validity error : ID ID01 already defined
Document idtest.xml does not validate
格式良好的XML文档:
<!DOCTYPE root SYSTEM "idtest.dtd">
<root>
<book book_id="ID01" />
<magazine magazine_id="ID01" />
</root>
DTD:
<!ELEMENT root ANY>
<!ELEMENT book ANY>
<!ATTLIST book book_id ID #IMPLIED>
<!ELEMENT magazine ANY>
<!ATTLIST magazine magazine_id ID #IMPLIED>
xmllint的输出:
$ xmllint --postvalid idtest.xml
<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "idtest.dtd">
<root>
<book book_id="ID01"/>
<magazine magazine_id="ID01"/>
</root>
idtest.xml:4: element magazine: validity error : ID ID01 already defined
<magazine magazine_id="ID01" />
^
idtest.xml:4: element magazine: validity error : ID ID01 already defined
Document idtest.xml does not validate
结论:更改属性名称没有帮助。类型是重要的。 ID类型的属性值必须是唯一的。解释1是正确的。