You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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>

关键修改说明

  1. 启用XSD 1.1:

    • 添加版本约束vc:minVersion="1.1",同时引入版本控制命名空间xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
    • 确保你的XML校验工具支持XSD 1.1(比如Saxon、Xerces2等)
  2. 调整action元素的出现次数:

    • 原XSD中<element name="action">默认是maxOccurs="1",改为maxOccurs="unbounded"以支持多个action元素
  3. 添加断言规则:

    • 第一个断言确保第一个action的no属性为1
    • 第二个断言遍历从第2个开始的每个action,验证其no值等于前一个action的no值加1,实现连续递增的校验

校验效果

  • 符合规则的XML(如你提供的示例)会通过校验
  • 以下情况会触发校验失败:
    • 第一个action的no不是1(比如no="2")
    • 中间出现跳号(比如1、3、4)
    • 顺序颠倒(比如2、1、3)
    • 出现重复的no值(比如1、1、2)

内容的提问来源于stack exchange,提问作者Christian Rockrohr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 23:06:12