如何在XSD中定义带属性元素顺序并验证no属性连续性?
如何在XSD中校验action元素no属性的连续递增顺序?
需求说明
需要确保<input>下的<action>元素的no属性满足:
- 从1开始
- 严格按1、2、3……连续递增,无数字缺失或跳号
不符合上述规则时,XSD校验失败。
原XSD的局限
你当前的XSD仅限制了no属性的取值范围(1-99),但无法校验跨元素的顺序和连续性——这是因为XSD 1.0不支持这类跨节点的约束逻辑,必须使用XSD 1.1的断言(assert)功能来实现。
修改后的完整XSD代码
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://your-namespace-here" targetNamespace="http://your-namespace-here" elementFormDefault="qualified" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1"> <xs:complexType name="action"> <xs:attribute name="no" use="required"> <xs:simpleType> <xs:restriction base="xs:int"> <xs:minInclusive value="1"/> <xs:maxInclusive value="99"/> <xs:whiteSpace value="collapse"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="type" type="xs:string"/> </xs:complexType> <xs:complexType name="input"> <xs:sequence> <xs:element name="action" type="tns:action" maxOccurs="unbounded"/> </xs:sequence> <!-- 核心校验断言 --> <xs:assert test="action[1]/@no = 1"/> <xs:assert test="every $pos in 2 to count(action) satisfies action[$pos]/@no = action[$pos - 1]/@no + 1"/> </xs:complexType> </xs:schema>
关键修改说明
启用XSD 1.1:
- 添加版本约束
vc:minVersion="1.1",同时引入版本控制命名空间xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" - 确保你的XML校验工具支持XSD 1.1(比如Saxon、Xerces2等)
- 添加版本约束
调整action元素的出现次数:
- 原XSD中
<element name="action">默认是maxOccurs="1",改为maxOccurs="unbounded"以支持多个action元素
- 原XSD中
添加断言规则:
- 第一个断言确保第一个action的
no属性为1 - 第二个断言遍历从第2个开始的每个action,验证其
no值等于前一个action的no值加1,实现连续递增的校验
- 第一个断言确保第一个action的
校验效果
- 符合规则的XML(如你提供的示例)会通过校验
- 以下情况会触发校验失败:
- 第一个action的
no不是1(比如no="2") - 中间出现跳号(比如
1、3、4) - 顺序颠倒(比如
2、1、3) - 出现重复的
no值(比如1、1、2)
- 第一个action的
内容的提问来源于stack exchange,提问作者Christian Rockrohr
相关产品推荐
相关产品推荐

