nonNegativeInteger 是 W3C 定义的内置原子类型,表示 ≥0 的整数(0, 1, 2, …),直接声明 type="xs:nonNegativeInteger" 即可,无需 restriction;它比 integer 严格(排除负数)、比 unsignedInt 宽松(无上界),仅当需额外范围限制(如 0–150)时才用 restriction。

nonNegativeInteger 是 XSD 内置类型,直接使用即可
不需要自定义复杂 restriction,nonNegativeInteger 已是 W3C XML Schema 定义的内置原子类型,对应数学上的 ℕ(0, 1, 2, …)。它比 integer 更严格,排除所有负数,但允许 0。
在 element 中直接声明 type="nonNegativeInteger"
最简方式是直接赋值给 type 属性。注意它属于 http://www.w3.org/2001/XMLSchema 命名空间,通常用前缀 xsd 或 xs 绑定:
<xs:element name="age" type="xs:nonNegativeInteger"/>
这样声明后,XML 实例中该元素只能接受 0、42、999 等值,而 -5、3.14、abc 均校验失败。
与 integer、unsignedInt 的关键区别
容易混淆的三个类型实际范围不同:
-
integer:…, -2, -1, 0, 1, 2, …(无限整数) -
nonNegativeInteger:0, 1, 2, 3, …(≥ 0,无上界) -
unsignedInt:0 到 2³²−1(即 0 到 4294967295,有明确上界)
若业务要求“年龄不能为负但理论上可超 40 亿”,必须用 nonNegativeInteger;若需强制限制在 32 位无符号整数范围内,才选 unsignedInt。
需要额外约束时再加 restriction
仅当还需限定取值范围(如“年龄必须在 0–150 之间”)才引入 restriction:
<xs:simpleType name="validAge">
<xs:restriction base="xs:nonNegativeInteger">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="150"/>
</xs:restriction>
</xs:simpleType>
注意:minInclusive 设为 0 是冗余的(nonNegativeInteger 已保证),真正起作用的是 maxInclusive。省略 minInclusive 不影响语义。
很多人误以为要手动写 pattern 或 minExclusive 来实现非负,其实徒增复杂度且易出错。XSD 类型系统已覆盖这个常见需求,直接用 nonNegativeInteger 就行——除非你正在对接一个不支持该内置类型的老旧校验器,那种情况得另想办法。










