元素声明

XML Schema 教程 · 第 2 章 · 10 次浏览

一个 XSD 文件的结构:根元素 xs:schema,里面声明元素和类型。元素声明指定名字和类型,复杂类型用 complexType 包子元素。

schema 根

xmlns:xs="http://www.w3.org/2001/XMLSchema" 声明标准命名空间,targetNamespace 指定本 Schema 定义的命名空间(可选)。

元素声明

<xs:element name="price" type="xs:decimal"/>。复杂元素用 complexType 定义子元素结构。

代码示例

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <!-- 全局元素:bookstore -->
  <xs:element name="bookstore">
    <xs:complexType>
      <xs:sequence>
        <!-- 子元素 book,可重复 1 到无限次 -->
        <xs:element name="book" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="title" type="xs:string"/>
              <xs:element name="author" type="xs:string"/>
              <xs:element name="price" type="xs:decimal"/>
            </xs:sequence>
            <xs:attribute name="category" type="xs:string"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>