XML Schema教程
什么是Schema
XML Schema 描述了 XML文档的结构。
学习目标
-
读取XML Schema
-
创建XML Schema
-
使用XML Schema
示例:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML Schema简介
-
XML Schema 是基于 XML 的 DTD 替代者。
-
XML Schema 可描述 XML 文档的结构。
-
XML Schema 语言也可作为 XSD(XML Schema Definition)来引用。
什么是XML Schema
定义:
作用:
XML Schema:
-
定义可出现在文档中的元素
-
定义可出现在文档中的属性
-
定义哪个元素是子元素
-
定义子元素的次序
-
定义子元素的数目
-
定义元素是否为空,或者是否可包含文本
-
定义元素和属性的数据类型
-
定义元素和属性的默认值以及固定值
XSD的使用
XML 文档可对 DTD 或 XML Schema 进行引用。
实例:
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
特点:
-
名为 "note.dtd" 的 DTD 文件,它对上面那个 XML 文档( "note.xml" )的元素进行了定义
-
第 1 行定义 note 元素有四个子元素:"to, from, heading, body"。
-
第 2-5 行定义了 to, from, heading, body 元素的类型是 "#PCDATA"。
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
特点:
下面是XML对它们的引用:
对DTD的引用
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM
"http://www.w3schools.com/dtd/note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
对XML Schema的引用
<?xml version="1.0"?>
<note
xmlns="http://www.w3schools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3schools.com note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>