XSD 属性

All attributes are declared as simple types.
所有属性都是以简单类型来声明的。


What is an Attribute?
属性是什么?

Simple elements cannot have attributes. If an element has attributes, it is considered to be of a complex type. But the attribute itself is always declared as a simple type.
简单的元素没有属性。当元素含有属性时,它会被认为是复合元素。但属性本身总是被声明为简单类型。


How to Define an Attribute?
怎么样定义属性?

The syntax for defining an attribute is:
定义一项属性的语法是:

<xs:attribute name="xxx" type="yyy"/>

where xxx is the name of the attribute and yyy specifies the data type of the attribute.
其中,xxx是属性的名称,yyy指定了属性的数据类型

XML Schema has a lot of built-in data types. The most common types are:
XML Schema本身有很多数据类型。最常见的数据类型有:

  • xs:string
    xs:字符串
  • xs:decimal
    xs:小数
  • xs:integer
    xs:整数
  • xs:boolean
    xs:逻辑值
  • xs:date
    xs:日期
  • xs:time
    xs:时间

Example
例子

Here is an XML element with an attribute:
这是一个有属性的XML元素:

<lastname lang="EN">Smith</lastname>

And here is the corresponding attribute definition:
而这个相应的属性定义:

<xs:attribute name="lang" type="xs:string"/>

Default and Fixed Values for Attributes
属性的默认值和固定值

Attributes may have a default value OR a fixed value specified.
属性也许有指定的默认值或固定值

A default value is automatically assigned to the attribute when no other value is specified.
值没有被指定时,属性自动会设成默认值

In the following example the default value is "EN":
下面例子里默认值是"EN":

<xs:attribute name="lang" type="xs:string" default="EN"/>

A fixed value is also automatically assigned to the attribute, and you cannot specify another value.
固定值是也是自动分派给属性的,并且,一旦有了固定值,你就不能指定其他值了。

In the following example the fixed value is "EN":
下面例子里固定值是"EN":

<xs:attribute name="lang" type="xs:string" fixed="EN"/>

Optional and Required Attributes
任意属性和必需属性

Attributes are optional by default. To specify that the attribute is required, use the "use" attribute:
默认时属性是任意的,要指明属性是必需的,须用到"use"属性

<xs:attribute name="lang" type="xs:string" use="required"/>

Restrictions on Content
对内容的约束

When an XML element or attribute has a data type defined, it puts restrictions on the element's or attribute's content.
当XML元素或属性有了已定义的数据类型,元素或属性的内容会有约束

If an XML element is of type "xs:date" and contains a string like "Hello World", the element will not validate.
如果一个XML元素是"xs:date"类型,并包含着象"Hello World"的字符串,元素就不会进行检验

With XML Schemas, you can also add your own restrictions to your XML elements and attributes. These restrictions are called facets. You can read more about facets in the next chapter.
你也可以用XML Schema给XML元素和属性添加约束限制。这些约束称为“面(facet)”。在下章里你可以读到更多关于“面”的内容


如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。