【问题标题】:How to define maxOccurs anywhere in element's scope in XML Schema?如何在 XML Schema 中元素范围内的任何位置定义 maxOccurs?
【发布时间】:2019-05-05 06:38:45
【问题描述】:
我想知道是否有办法在abc 元素中定义content 的maxOccurs?在a、b 和c 中有多少content 元素并不重要,只要在整个abc 中出现的次数不超过x 次即可。提前致谢!
<abc>
<a>
<content>AA</content>
<content>AAA</content>
</a>
<b>
<content>B</content>
</b>
<c>
<content>CCC</content>
<content>C</content>
</c>
</abc>
【问题讨论】:
标签:
xml
xsd
xsd-validation
xml-validation
【解决方案1】:
XSD 1.0
不可能。必须在 XSD 中进行带外检查。
XSD 1.1
可以使用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="abc">
<xs:complexType>
<xs:sequence>
<xs:element name="a" type="HasContentType"/>
<xs:element name="b" type="HasContentType"/>
<xs:element name="c" type="HasContentType"/>
</xs:sequence>
<xs:assert test="count(*/content) <= 5"/>
</xs:complexType>
</xs:element>
<xs:complexType name="HasContentType">
<xs:sequence>
<xs:element name="content" type="xs:string"
minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
注意:上述断言限制了abc 的子元素中出现的content 元素的总数。如果您想限制 abc 下层次结构中的任何位置的出现,正如您的标题所暗示的那样,元素范围内的任何地方,您可以改用以下断言:
<xs:assert test="count(.//content) <= 5"/>