XML Schema(XSD)完整支持的数据类型一览
XML Schema 内置了 45 种标准数据类型(XSD 1.0 + 1.1),远超 DTD 的“只有文本”。这些类型直接决定了 XML 内容在验证时能否通过、能否被编程语言自动映射为 int、DateTime、BigDecimal 等。
下面按实际使用频率和类别整理,最常用的前 15 种已加粗高亮。
1. 最常用内置简单类型(90% 项目都用这些)
| 类型名称 | 含义 | 示例值 | 典型用途 |
|---|---|---|---|
| xs:string | 普通字符串 | 张三、Hello World、 | 姓名、描述、任意文本 |
| xs:boolean | 布尔值 | true、false、1、0 | 开关、是否删除 |
| xs:decimal | 任意精度十进制数 | 99.99、-100、0.001 | 价格、金额(推荐!) |
| xs:integer | 任意大小整数 | -100、0、999999999999 | 数量、ID(逻辑主键) |
| xs:int | 32位有符号整数 | -2147483648 ~ 2147483647 | 年龄、状态码 |
| xs:long | 64位有符号整数 | 可达 ±9×10¹⁸ | 大型计数器 |
| xs:date | 日期(无时区) | 2025-11-28 | 生日、订单日期 |
| xs:time | 时间(无时区) | 14:30:25 | 开门时间 |
| xs:dateTime | 日期+时间(可带时区) | 2025-11-28T14:30:25Z | 下单时间、日志时间(最常用) |
| xs:dateTimeStamp | 日期+时间+必须有时区 | 2025-11-28T14:30:25+08:00 | 金融、日志强制要求 |
| xs:positiveInteger | 正整数(≥1) | 1、100 | 数量、行号 |
| xs:nonNegativeInteger | 非负整数(≥0) | 0、1、100 | 库存、页码 |
| xs:byte | 8位有符号整数 | -128 ~ 127 | 小状态码 |
| xs:short | 16位有符号整数 | -32768 ~ 32767 | |
| xs:unsignedInt | 32位无符号整数 | 0 ~ 4294967295 | IPv4 地址常用 |
2. 其他常用但不那么频繁的类型
| 类型名称 | 含义 | 示例 |
|---|---|---|
| xs:float | 32位浮点(IEEE 754) | 3.14、-1E4、INF、NaN |
| xs:double | 64位浮点(推荐代替 float) | 3.141592653589793 |
| xs:duration | 时间段 | P1Y2M3DT4H5M6S(1年2月3天4小时5分6秒) |
| xs:gYear | 年份 | 2025、-0050 |
| xs:gYearMonth | 年-月 | 2025-11 |
| xs:anyURI | URL/URI | https://example.com、../file.xml |
| xs:base64Binary | Base64 编码的二进制 | SGVsbG8= |
| xs:hexBinary | 十六进制二进制 | 0FB7 |
| xs:ID | XML 文档内唯一标识符 | person_001(类似 HTML id) |
| xs:IDREF / xs:IDREFS | 引用 ID | person_001 |
| xs:NMTOKEN / xs:NMTOKENS | 合法 XML 名令牌 | order-no |
| xs:language | 语言代码 | zh-CN、en-US |
| xs:normalizedString | 已标准化空白的字符串 | (空格被保留但不折叠) |
| xs:token | 去掉首尾空格、连续空格变单个 | (最常用做枚举字符串) |
3. XSD 1.1 新增类型(部分工具已支持)
| 类型名称 | 含义 |
|---|---|
| xs:dayTimeDuration | 只含天时分秒的 duration(常用于超时) |
| xs:yearMonthDuration | 只含年月的 duration |
| xs:precisionDecimal | 更高精度十进制(未来可能替代 decimal) |
4. 实际项目中最推荐的金额、数量、时间写法
<!-- 金额(推荐) -->
<price>99.99</price>
<xs:element name="price" type="xs:decimal"/>
<!-- 数量(推荐) -->
<quantity>99</quantity>
<xs:element name="quantity" type="xs:positiveInteger"/>
<!-- 时间(推荐) -->
<createTime>2025-11-28T14:30:25+08:00</createTime>
<xs:element name="createTime" type="xs:dateTime"/>
5. 自定义类型(基于内置类型再限制)
<!-- 性别枚举 -->
<xs:simpleType name="GenderType">
<xs:restriction base="xs:string">
<xs:enumeration value="male"/>
<xs:enumeration value="female"/>
<xs:enumeration value="other"/>
</xs:restriction>
</xs:simpleType>
<!-- 金额鉴金额:2位小数 -->
<xs:simpleType name="MoneyType">
<xs:restriction base="xs:decimal">
<xs:fractionDigits value="2"/>
<xs:totalDigits value="12"/>
</xs:restriction>
</xs:simpleType>
总结:日常开发记住下面这 10 个就完全够用(覆盖 99% 场景):
- xs:string
- xs:boolean
- xs:decimal(金额)
- xs:integer / xs:int
- xs:positiveInteger(数量)
- xs:date
- xs:dateTime
- xs:anyURI
- xs:base64Binary
- xs:ID / xs:IDREF
其他类型属于“知道有就行,真正用到的机会很少”。有具体业务想定义类型,可以直接告诉我,我帮你写最合适的 XSD 类型。