假设我有一个这样的 XML 文件:
<?xml version="1.0" encoding="utf-8" ?>
<Books>
<Book
Title="Animal Farm"
Author="George Orwell"
/>
</Books>
是否可以为这个 XML 文件创作一个 XSD,上面写着:如果 Book 元素具有 Title 属性,那么 Author 属性也必须存在?请注意,我不是在询问基于属性值的限制,而是基于属性名称。
在 XSD 1.0中,您必须在应用程序级别施加该约束。
在 XSD 1.1中,您可以使用xs:assert
来施加约束:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Books">
<xs:complexType>
<xs:sequence>
<xs:element name="Book" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="Title"/>
<xs:attribute name="Author"/>
<xs:assert test="not(@Title) or @Author"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>