XSD使用特定属性限制元素的出现
问题描述:
我尝试为可包含不同类型条目的选择定义复杂类型 但只有一个条目被允许具有属性“multiselect”。XSD使用特定属性限制元素的出现
这里是我的尝试:
<element name="selection" minOccurs="0" maxOccurs="unbounded">
<complexType>
<sequence>
<element name="name" type="string" />
<element name="source">
<complexType>
<choice>
<element name="item" minOccurs="1" maxOccurs="unbounded" type="string" />
<element name="path" type="string" minOccurs="1" maxOccurs="1" />
</choice>
</complexType>
</element>
</sequence>
<attribute name="multiselection" type="boolean" minOccurs="1" maxOccurs="1" />
</complexType>
</element>
的结果应该是有可能的“选择”更多的元素,其中如果源类型是“项目”或类型的也没关系“路径”。但是只有一个“选择”元素被允许具有属性multiselection = true。
但是,因为它似乎没有属性的min-/maxOccures。 我该如何解决这个问题?
THX
答
首先,最小/ maxOccurs的被保留用于颗粒(本地元素,元素的引用,组参考文献,序列,选择)。一个属性出现由
use = (optional | prohibited | required)控制 - 默认值是可选的
为了进一步约束该一组元素中,只有一个可以具有与真正的逻辑值(可以是1或指定的属性文字true
) - 这是你不能用XSD 1.0单独做的事情。您可以在XSD上使用Schematron。
或者,您可以在XSD 1.1中轻松实现此目的。
<?xml version="1.0" encoding="utf-8" ?>
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) -->
<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="sample">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="selection" minOccurs="0" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="source">
<xsd:complexType>
<xsd:choice>
<xsd:element name="item" minOccurs="1" maxOccurs="unbounded" type="xsd:string"/>
<xsd:element name="path" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:attribute name="multiselection" type="xsd:boolean" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:assert test="count(selection[@multiselection=true()])=1"/>
</xsd:complexType>
</xsd:element>
</xsd:schema>
沿着这些线路(包括虚假或两者真会失败验证)的东西:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<sample xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<selection multiselection="false">
<name>name1</name>
<source>
<item>item1</item>
<item>item1</item>
</source>
</selection>
<selection multiselection="false">
<name>name1</name>
<source>
<item>item1</item>
<item>item1</item>
</source>
</selection>
</sample>
cvc-assertion.3.13.4.1: Assertion evaluation ('count(selection[@multiselection=true()])=1') for element 'sample' with type '#anonymous' did not succeed.
使它们成为一个true
应该得到成功验证。
你需要更好地解释。也许举一个有效和无效的实例文档的例子。 “multiselect”属性继续哪个元素? – 2013-03-11 12:29:11
我还没有测试过这个,但是尝试在属性值上设置一个'唯一'约束,然后将属性限制为单个值。 – 2013-03-11 13:55:22