XML Schema attribute 元素
❮ 完整的 XML Schema 参考
定义和用法
attribute 元素定义一个属性。
元素信息
- 父元素: attributeGroup, schema, complexType, restriction (包括 simpleContent 和 complexContent), extension (包括 simpleContent 和 complexContent)
语法
<attribute
default=string
fixed=string
form=qualified|unqualified
id=ID
name=NCName
ref=QName
type=QName
use=optional|prohibited|required
任何属性
>
(annotation?,(simpleType?))
</attribute>
(问号表示该元素可以在 attribute 元素中出现零次或一次)
Attribute | 描述 |
---|---|
default | 可选。指定属性的默认值。default 和 fixed 属性不能同时存在 |
fixed | 可选。指定属性的固定值。default 和 fixed 属性不能同时存在 |
form | 可选。指定属性的形式。默认值是包含该属性的元素的 attributeFormDefault 属性的值。可以设置为以下之一:
|
id | 可选。指定元素的唯一 ID |
name | 可选。指定属性的名称。name 和 ref 属性不能同时存在 |
ref | 可选。指定对命名属性的引用。name 和 ref 属性不能同时存在。如果存在 ref,则不能存在 simpleType 元素、form 和 type |
type | 可选。指定内置数据类型或简单类型。type 属性只能在内容不包含 simpleType 元素时存在 |
use | 可选。指定属性的使用方式。可以是以下值之一:
|
任何属性 | 可选。指定任何其他非 schema 命名空间的属性 |
示例 1
<xs:attribute name="code">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z][A-Z]"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
上面的示例表明 "code" 属性有一个限制。唯一可接受的值是两个大写字母(a 到 z)。
示例 2
要在复杂类型中使用现有属性定义声明属性,请使用 ref 属性
<xs:attribute name="code">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z][A-Z]"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:complexType name="someComplexType">
<xs:attribute ref="code"/>
</xs:complexType>
示例 3
属性可以指定默认值或固定值。当未指定其他值时,默认值会自动分配给该属性。在以下示例中,默认值为 "EN"
<xs:attribute name="lang" type="xs:string" default="EN"/>
当未指定其他值时,固定值也会自动分配给该属性。但与默认值不同的是,如果您指定了与固定值不同的值,则文档将被视为无效。在以下示例中,固定值为 "EN"
<xs:attribute name="lang" type="xs:string" fixed="EN"/>
示例 4
所有属性默认都是可选的。要明确指定属性是可选的,请使用 "use" 属性
<xs:attribute name="lang" type="xs:string" use="optional"/>
使属性成为必需
<xs:attribute name="lang" type="xs:string" use="required"/>
❮ 完整的 XML Schema 参考