在XML Schema(XSD)里,xs:attribute用来定义XML元素的属性,而它的type属性则决定了该属性值必须遵循的数据格式。type可以直接引用W3C定义的内置简单类型,也可以通过name自定义简单类型后再引用。

xs:attribute的type支持的内置类型
XSD规范提供了一组内置简单类型,最常见且可直接用于type属性的包括:
- xs:string:字符串类型,不做任何格式限制
- xs:boolean:布尔值,只能是true或false
- xs:integer:整数类型
- xs:decimal:十进制数
- xs:date:日期,格式为YYYY-MM-DD
- xs:anyURI:统一资源标识符
使用内置类型的示例
下面这段Schema定义了一个book元素,它拥有category和price两个属性,分别使用xs:string和xs:decimal进行约束:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="book">
<xs:complexType>
<xs:attribute name="category" type="xs:string" use="required"/>
<xs:attribute name="price" type="xs:decimal" use="optional"/>
</xs:complexType>
</xs:element>
</xs:schema>
引用自定义简单类型
当内置类型无法满足需求时,可以先定义简单类型,再在type中引用:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="colorType">
<xs:restriction base="xs:string">
<xs:enumeration value="red"/>
<xs:enumeration value="green"/>
<xs:enumeration value="blue"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="item">
<xs:complexType>
<xs:attribute name="color" type="colorType" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
type属性的注意事项
需要注意,xs:attribute的type只能指向简单类型,不能指向复杂类型。如果属性需要包含子结构,则应当改用元素而非属性来表示。另外,若省略type属性,也可以内联使用<xs:simpleType>直接定义,例如:
<xs:attribute name="level" use="required">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="1"/>
<xs:maxInclusive value="10"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
常见内置类型对照表
| 类型名称 | 说明 | 示例值 |
|---|---|---|
| xs:string | 字符串 | hello |
| xs:int | 32位整数 | 100 |
| xs:double | 双精度浮点 | 3.14 |
| xs:dateTime | 日期时间 | 2023-08-01T12:00:00 |
掌握xs:attribute中type的可选数据类型,能让你在编写XML Schema时更准确地约束数据,减少后期解析和校验中的问题。
XML_Schemaxs:attributeXSD数据类型修改时间:2026-07-27 18:36:33