XSD中抽象类型通过abstract="true"定义,不可直接实例化,仅能被extension或restriction继承;抽象复杂类型常用于构建类型体系,抽象简单类型仅支持restriction继承且不可被union或list引用。

在XSD中定义抽象类型,只需在 或 元素上设置 abstract="true" 属性即可。抽象类型不能直接用于元素实例,只能被其他类型通过 extension 或 restriction 继承。
定义抽象复杂类型
这是最常见的情况,用于构建可扩展的类型体系:
<font size="2"><complextype name="Person" abstract="true"><sequence><element name="name" type="xs:string"></element><element name="age" type="xs:integer"></element></sequence></complextype><complextype name="Employee"><complexcontent><extension base="Person"><sequence><element name="employeeId" type="xs:string"></element></sequence></extension></complexcontent></complextype></font>
此时 元素不能直接出现在XML文档中,但 可以,并自动包含 name 和 age。
定义抽象简单类型
较少见但合法,适用于需要统一约束但不直接使用的值类型:
<font size="2"><simpletype name="Identifier" abstract="true"><restriction base="xs:string"><pattern value="[A-Za-z][A-Za-z0-9_]*"></pattern></restriction></simpletype><simpletype name="UserId"><restriction base="Identifier"><maxlength value="16"></maxlength></restriction></simpletype></font>
注意:抽象简单类型不能被 xs:union 或 xs:list 直接引用,仅支持 restriction 继承。
配合 xsi:type 使用抽象类型
当元素声明使用抽象类型作为 type 时,XML实例必须通过 xsi:type 指定具体子类型:
<font size="2"><element name="person" type="Person"></element></font>
对应合法XML示例:
<font size="2"><person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Employee"><name>Alice</name><age>30</age><employeeid>E123</employeeid></person></font>
若省略 xsi:type 或指定为抽象类型名,校验将失败。
关键注意事项
- 抽象类型本身不能出现在
的type属性中,除非该元素允许运行时动态类型(即依赖xsi:type) - 抽象类型可以有
final属性(如final="#all"),限制后续继承方式 - 抽象类型可以有
block属性,防止被某些方式(如 substitution group)替代 - 抽象类型不强制要求有子类型,但没有子类型时它就完全不可用
基本上就这些。抽象类型本质是建模上的“占位符”,核心作用是规范继承结构,不是为了单独使用。










