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

如何定义支持单个数值或指定范围的XSD Restriction约束

你可以通过XSD的<xsd:union>(联合类型)实现两种约束的或逻辑合并,联合类型的取值可以匹配其成员类型中的任意一个,刚好符合你的需求。

实现方式

你可以先分别定义两个独立的约束类型,再通过联合类型合并即可,完整示例如下:

<!-- 定义0-100区间的约束类型 -->
<xsd:simpleType name="Range0To100Type">
  <xsd:restriction base="xsd:double">
    <xsd:minInclusive value="0.0"/>
    <xsd:maxInclusive value="100.0"/>
  </xsd:restriction>
</xsd:simpleType>

<!-- 定义仅允许-1的约束类型 -->
<xsd:simpleType name="MinusOneType">
  <xsd:restriction base="xsd:double">
    <xsd:enumeration value="-1.0"/>
  </xsd:restriction>
</xsd:simpleType>

<!-- 用联合类型合并两个约束,逻辑为OR -->
<xsd:simpleType name="CustomNumberType">
  <xsd:union memberTypes="Range0To100Type MinusOneType"/>
</xsd:simpleType>

后续直接用合并后的自定义类型约束你的XML字段即可:

<xsd:element name="yourField" type="CustomNumberType"/>

如果你不想单独定义多个子类型,也可以直接把约束内嵌到union节点中:

<xsd:simpleType name="CustomNumberType">
  <xsd:union>
    <xsd:simpleType>
      <xsd:restriction base="xsd:double">
        <xsd:minInclusive value="0.0"/>
        <xsd:maxInclusive value="100.0"/>
      </xsd:restriction>
    </xsd:simpleType>
    <xsd:simpleType>
      <xsd:restriction base="xsd:double">
        <xsd:enumeration value="-1.0"/>
      </xsd:restriction>
    </xsd:simpleType>
  </xsd:union>
</xsd:simpleType>

配置完成后,对应字段的取值仅允许为-1或者0到100之间的数值,其余值都会触发校验失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:36:03