XML Schema 教程

XML Schema(XSD)完整教程,从入门到精通

XML Schema(简称 XSD:XML Schema Definition)是 W3C 推荐的用来替代 DTD 的模式语言,用于严格定义 XML 文档的结构、数据类型和约束条件。它功能远强于 DTD,是目前企业级 XML 应用的标配。

1. 为什么选择 XML Schema 而不是 DTD?

特性DTDXML Schema (XSD)
本身是否是 XML不是是(用 XML 语法写)
数据类型支持几乎没有丰富的内置类型(string、int、date 等)
命名空间支持不支持完美支持
可扩展性极强(支持继承、派生类型等)
工具支持越来越少所有主流 IDE、解析器都支持

2. 一个最简单的 XSD 示例

假设我们要定义一个图书清单 XML:

<!-- books.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="books.xsd">
    <book id="001">
        <title>XML 入门</title>
        <author>张三</author>
        <price>68.00</price>
    </book>
</books>

对应的 XSD(books.xsd):

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

    <!-- 根元素 books -->
    <xs:element name="books">
        <xs:complexType>
            <xs:sequence>
                <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="id" type="xs:string" use="required"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>

3. XSD 核心组件详解

3.1 基本结构

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://example.com/books"
           elementFormDefault="qualified">

    <!-- 这里写元素、类型定义 -->

</xs:schema>

常用属性说明:

  • targetNamespace:定义这个 XSD 所属的命名空间
  • elementFormDefault="qualified":表示所有元素必须带命名空间前缀(推荐)
  • attributeFormDefault="unqualified":属性通常不需要前缀

3.2 内置简单类型(部分常用)

类型说明示例
xs:string字符串“hello”
xs:integer整数100
xs:int32位整数-1, 0, 999
xs:decimal十进制数68.00
xs:boolean布尔值true/false
xs:date日期2025-11-28
xs:time时间14:30:25
xs:dateTime日期时间2025-11-28T14:30:25Z
xs:duration时间段P1Y2M3DT4H5M6S
xs:anyURIURLhttp://example.com

3.3 复杂类型(complexType)

<!-- 匿名复杂类型(最常见) -->
<xs:element name="person">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="age" type="xs:int"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<!-- 命名复杂类型(可复用) -->
<xs:complexType name="AddressType">
    <xs:sequence>
        <xs:element name="country" type="xs:string"/>
        <xs:element name="city" type="xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:element name="company">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="address" type="AddressType"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

3.4 元素出现次数控制

属性含义默认值
minOccurs最小出现次数1
maxOccurs最大出现次数(可为 unbounded)1

示例:0 到多个

<xs:element name="phone" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>

3.5 属性声明

<xs:attribute name="id" type="xs:string" use="required"/>
<xs:attribute name="status" type="xs:string" use="optional" default="active"/>
<xs:attribute name="deleted" type="xs:boolean" use="optional" fixed="false"/>

use 可选值:requiredoptionalprohibited

4. 命名空间(Namespace)详解

情况1:没有命名空间(最简单)

XSD:

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

XML:

<books xsi:noNamespaceSchemaLocation="books.xsd">

情况2:有目标命名空间(企业推荐做法)

XSD(books.xsd):

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://www.example.com/books"
           xmlns:bk="http://www.example.com/books"
           elementFormDefault="qualified">

    <xs:element name="books" type="bk:BooksType"/>

    <xs:complexType name="BooksType">
        <xs:sequence>
            <xs:element name="book" type="bk:BookType" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>

    <xs:complexType name="BookType">
        <!-- ... -->
    </xs:complexType>

</xs:schema>

XML:

<?xml version="1.0" encoding="UTF-8"?>
<bk:books xmlns:bk="http://www.example.com/books"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.example.com/books books.xsd">

    <bk:book id="001">
        <bk:title>Java编程思想</bk:title>
    </bk:book>

</bk:books>

5. 自定义简单类型(限制 – restriction)

<!-- 性别只能限定为 male/female -->
<xs:simpleType name="GenderType">
    <xs:restriction base="xs:string">
        <xs:enumeration value="male"/>
        <xs:enumeration value="female"/>
    </xs:restriction>
</xs:simpleType>

<!-- 价格必须在 0-1000 之间 -->
<xs:simpleType name="PriceType">
    <xs:restriction base="xs:decimal">
        <xs:minInclusive value="0"/>
        <xs:maxExclusive value="1000"/>
    </xs:restriction>
</xs:simpleType>

<!-- 正则表达式限制(邮编示例) -->
<xs:simpleType name="PostcodeType">
    <xs:restriction base="xs:string">
        <xs:pattern value="[0-9]{6}"/>
    </xs:restriction>
</xs:simpleType>

常用 facet(约束):

  • length、minLength、maxLength
  • pattern(正则)
  • enumeration
  • minInclusive、maxInclusive、minExclusive、maxExclusive
  • totalDigits、fractionDigits

6. 元素和属性的引用(ref)

<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:int"/>

<xs:element name="person">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="name"/>
            <xs:element ref="age"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

7. 继承(extension & restriction)

7.1 复杂类型扩展(添加新元素)

<xs:complexType name="Person">
    <xs:sequence>
        <xs:element name="name" type="xs:string"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="Employee">
    <xs:complexContent>
        <xs:extension base="Person">
            <xs:sequence>
                <xs:element name="employeeId" type="xs:string"/>
                <xs:element name="department" type="xs:string"/>
            </xs:sequence>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>

7.2 简单类型派生(restriction)

上面自定义 GenderType、PriceType 都是例子。

8. 常用完整实例:订单系统

<!-- order.xsd -->
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://example.com/order"
           xmlns:ord="http://example.com/order"
           elementFormDefault="qualified">

    <xs:element name="order">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="orderId" type="xs:string"/>
                <xs:element name="customer" type="ord:CustomerType"/>
                <xs:element name="items">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="item" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="productId" type="xs:string"/>
                                        <xs:element name="quantity" type="xs:positiveInteger"/>
                                        <xs:element name="price" type="xs:decimal"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="total" type="xs:decimal"/>
            </xs:sequence>
            <xs:attribute name="orderDate" type="xs:date" use="required"/>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="CustomerType">
        <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="email" type="xs:string"/>
            <xs:element name="phone" type="xs:string" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>

</xs:schema>

9. 验证工具推荐

  • 在线:https://www.xmlvalidation.com/
  • VS Code 插件:Red Hat XML
  • Java:javax.xml.validation.Validator
  • .NET:XmlSchemaSet
  • Python:lxml 库

10. 最佳实践总结

  1. 永远使用命名空间(targetNamespace)
  2. elementFormDefault=”qualified”
  3. 使用有意义的类型名(不要全用匿名类型)
  4. 尽量复用 complexType 和 simpleType
  5. 给重要元素添加 <xs:annotation><xs:documentation> 注释
  6. 使用版本控制(在文件名或命名空间中体现版本)
<xs:annotation>
    <xs:documentation>
        订单主元素,版本 v2.0,2025年更新
    </xs:documentation>
</xs:annotation>

这样,你就掌握了 90% 实际项目中用到的 XML Schema 知识了!有具体场景或报错可以继续问我,我可以帮你写或调试 XSD。

文章已创建 2783

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部