问题描述
我写了一个关于管理电影元素的 XSD。我的问题是,如果给定的 XML 文件没有提供属性类型,即 <genre />
:不应验证此语句。
我尝试了 <xs:assert>
来消除这种情况,但它没有验证。
简而言之:我希望我的 xsd 能够验证只有一种类型的电影。
<xs:element name="genre">
<xs:complexType>
<xs:attribute name="thriller" type="xs:string" use="optional" />
<xs:attribute name="horror" type="xs:string" use="optional" />
<xs:attribute name="scifi" type="xs:string" use="optional" />
<xs:attribute name="romance" type="xs:string" use="optional" />
<xs:attribute name="literature" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
谢谢。
解决方法
如果您使用的是 xsd 1.1,则可以使用 xs:key 来强制执行如下约束:
<xs:element name="movie">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="authors" type="xs:string"/>
<xs:element name="year_of_publication" type="xs:short"/>
<xs:element name="genre" >
<xs:complexType>
<xs:attribute name="romance" type="xs:string" use="optional"/>
<xs:attribute name="thriller" type="xs:string" use="optional"/>
<xs:attribute name="horror" type="xs:string" use="optional"/>
<xs:attribute name="scifi" type="xs:string" use="optional"/>
<xs:attribute name="literature" type="xs:string" use="optional"/>
</xs:complexType>
<xs:key name="OnlyOneGenreAttributePresent">
<xs:selector xpath="." />
<xs:field xpath="@romance | @thriller | @romance | @scifi | @literature " />
</xs:key>
</xs:element>
<xs:element name="edition" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
但如果可以,最好将 XML 结构更改为更“正确”的内容。例如,而不是:
<genre scifi="string" />
使用:
<genre>scifi<genre>
它将简化 xsd 并允许使用符合 xsd 1.0 的 xsd:
<xs:simpleType name="T_genres">
<xs:restriction base="xs:string">
<xs:enumeration value="thriller"/>
<xs:enumeration value="horror"/>
<xs:enumeration value="romance"/>
<xs:enumeration value="scifi"/>
<xs:enumeration value="literature"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="movie">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="authors" type="xs:string"/>
<xs:element name="year_of_publication" type="xs:short"/>
<xs:element name="genre" type="T_genres" />
<xs:element name="edition" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
创建一个全局的