在XML Schema的定义中,xs:documentation是W3C标准规定的用于添加结构化注释的标签,它属于xs:annotation标签的子元素,不会干扰Schema的语法校验逻辑,是官方推荐的XSD注释方式。

xs:documentation的基本使用规则
xs:documentation不能直接作为XSD的顶层元素存在,必须嵌套在<xs:annotation>标签内部,而<xs:annotation>可以放置在几乎所有XSD的结构定义元素中,比如元素声明、属性声明、复杂类型、简单类型、全局定义等位置。
基本语法结构如下:
<xs:element name="user" type="xs:string">
<xs:annotation>
<xs:documentation>
用户名称字段,长度限制为1到20个字符,不允许包含特殊符号
</xs:documentation>
</xs:annotation>
</xs:element>
xs:documentation的常用属性
xs:documentation支持两个可选属性,用于扩展注释的功能:
- source:用于指定注释信息的来源地址,比如相关文档的链接地址,该属性值不会被校验器解析,仅作为补充信息存在。
- xml:lang:用于指定注释内容的语言,比如xml:lang="zh-CN"表示注释是简体中文,xml:lang="en"表示注释是英文,支持多语言注释的场景。
不同场景下的注释示例
1. 为元素添加注释
为全局元素或者局部元素添加注释是最常见的使用场景,注释内容可以说明元素的用途、取值范围、约束条件等。
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/user"
xmlns="http://www.example.org/user"
elementFormDefault="qualified">
<!-- 全局元素添加注释 -->
<xs:element name="userInfo">
<xs:annotation>
<xs:documentation xml:lang="zh-CN">
用户信息根元素,包含用户的基本属性信息,如用户名、年龄、邮箱等
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<!-- 局部元素添加注释 -->
<xs:element name="username" type="xs:string">
<xs:annotation>
<xs:documentation>
用户名,长度1-20位,仅支持字母、数字和下划线
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="age" type="xs:int">
<xs:annotation>
<xs:documentation>
用户年龄,取值范围为1到120之间的整数
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
2. 为类型定义添加注释
无论是简单类型还是复杂类型,都可以在类型定义的开头添加注释,说明类型的设计意图和使用场景。
<xs:simpleType name="emailType">
<xs:annotation>
<xs:documentation xml:lang="zh-CN">
邮箱地址类型,符合标准邮箱格式校验规则,最大长度为50个字符
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}"/>
<xs:maxLength value="50"/>
</xs:restriction>
</xs:simpleType>
3. 多语言注释支持
如果Schema需要支持多语言场景,可以通过xml:lang属性为同一个结构添加不同语言的注释,工具可以根据语言配置展示对应的注释内容。
<xs:element name="productName" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="zh-CN">
产品名称,最长不超过30个字符
</xs:documentation>
<xs:documentation xml:lang="en">
Product name, maximum length is 30 characters
</xs:documentation>
</xs:annotation>
</xs:element>
注意事项
- xs:documentation的内容会被XML解析器当作文本内容处理,如果注释中包含XML特殊字符,比如<、>、&,需要进行转义,否则会导致Schema语法错误。
- xs:annotation标签下除了可以放xs:documentation,还可以放<xs:appinfo>标签,后者用于存放机器可读取的辅助信息,和xs:documentation的人类可读注释用途不同,不要混淆使用。
- 不要在xs:documentation中写入会影响Schema校验的内容,比如额外的元素定义、类型约束等,注释内容仅作为说明性文本存在。
- 当使用工具生成Schema文档时,xs:documentation的内容通常会被提取为API文档的说明部分,因此建议注释内容清晰、准确,避免模糊的描述。
XML_Schemaxs:documentationXSD注释xsd添加注释修改时间:2026-07-17 14:18:14