yco*_*omp 8 xml xsd xsd-validation
<tag name="default" abc="10" def="20> <!-- not valid, abc and def should be mutually exclusive -->
<tag name="default1" abc="10"> <!-- valid -->
<tag name="default2" def="20> <!-- valid -->
Run Code Online (Sandbox Code Playgroud)
我能放进我的XSD
,这样@abc
并@def
不能共存同一元素的属性?
如果它们在同一个元素上共存,那么验证会失败?
可以用巧妙的技巧来完成xs:key
.请参阅@ Kachna的回答.
请注意,如果某些解析器在多个选定值中未能失败,则可能会允许这两个属性xs:key
.至少有一个已知的案例发生在过去.
可以使用xs:assert
:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
vc:minVersion="1.1">
<xs:element name="tag">
<xs:complexType>
<xs:sequence/>
<xs:attribute name="name" type="xs:string"/>
<xs:attribute name="abc" use="optional" type="xs:integer"/>
<xs:attribute name="def" use="optional" type="xs:integer"/>
<xs:assert test="(@abc and not(@def)) or (not(@abc) and @def)"/>
</xs:complexType>
</xs:element>
</xs:schema>
Run Code Online (Sandbox Code Playgroud)
在XSD 1.0中,您可以使用xs:key
element。
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="tag">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="abc" type="xs:integer"/>
<xs:attribute name="def" type="xs:integer"/>
</xs:complexType>
<xs:key name="attributeKey">
<xs:selector xpath="."/>
<xs:field xpath="@abc|@def"/>
</xs:key>
</xs:element>
Run Code Online (Sandbox Code Playgroud)
编辑:
如果两个属性都存在(即使具有不同的值),这将创建两个键,因此XML验证将失败。另一方面,<xs: key>
要求为元素定义键,因此必须存在两个属性之一。
使用上述XSD的以下XML文档无效。(我正在使用oXygen 17.0):
<tag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="stack3.xsd" name="" abc="12" def="13"/>
Run Code Online (Sandbox Code Playgroud)
错误:
cvc-identity-constraint.3: Field "./@abc|./@def" of identity constraint "attributeKey" matches more than one value within the scope of its selector; fields must match unique values
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2040 次 |
最近记录: |