XSD中通过xs:simpleType和xs:restriction定义受限简单类型,支持maxLength、min/maxInclusive、enumeration、pattern等facet约束字符串长度、数值范围、枚举值及正则格式。

在XSD(XML Schema Definition)中定义一个简单类型并为其添加限制,主要通过 xs:simpleType 元素实现,并结合 xs:restriction 来约束基类型的行为。这种方式常用于限制字符串长度、数值范围、日期格式、枚举值等。
你可以从XSD的内置类型(如 xs:string、xs:integer、xs:date 等)派生出新的受限类型。
示例:定义一个受限的字符串类型,长度不超过10个字符
<xs:simpleType name="ShortString">
<xs:restriction base="xs:string">
<xs:maxLength value="10"/>
</xs:restriction>
</xs:simpleType>
可以组合多个限制来更精确地控制数据格式。
示例:定义年龄字段,限制为1到120之间的整数
<xs:simpleType name="AgeType">
<xs:restriction base="xs:integer">
<xs:minInclusive value="1"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType>
如果你希望字段只能取特定几个值,使用 xs:enumeration。
示例:定义性别类型,仅允许 'male' 或 'female'
<xs:simpleType name="GenderType">
<xs:restriction base="xs:string">
<xs:enumeration value="male"/>
<xs:enumeration value="female"/>
</xs:restriction>
</xs:simpleType>
对于复杂格式(如电话号码、邮编),可用 xs:pattern 配合正则表达式。
示例:定义中国邮政编码(6位数字)
<xs:simpleType name="ZipCodeType">
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]{6}"/>
</xs:restriction>
</xs:simpleType>
这些自定义的简单类型可以在元素或属性中引用:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="ShortString"/>
<xs:element name="age" type="AgeType"/>
<xs:element name="gender" type="GenderType"/>
<xs:element name="zip" type="ZipCodeType"/>
</xs:sequence>
</xs:complexType>
</xs:element>
以上就是如何在XSD中定义一个简单类型(simpleType),并为其添加限制?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号