Latest web development tutorials

如何使用XML Schema

XML 文檔可對DTD 或XML Schema 進行引用。


一個簡單的XML 文檔:

請看這個名為"note.xml" 的XML 文檔:

<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


DTD 文件

下面這個例子是名為"note.dtd" 的DTD 文件,它對上面那個XML 文檔( "note.xml" )的元素進行了定義:

<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

第1 行定義note 元素有四個子元素:"to, from, heading, body"。

第2-5 行定義了to, from, heading, body 元素的類型是"#PCDATA"。


XML Schema

下面這個例子是一個名為"note.xsd" 的XML Schema 文件,它定義了上面那個XML 文檔( "note.xml" )的元素:

<?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>

note 元素是一個複合類型,因為它包含其他的子元素。 其他元素(to, from, heading, body) 是簡易類型,因為它們沒有包含其他元素。 您將在下面的章節學習更多有關複合類型和簡易類型的知識。


對DTD 的引用

此文件包含對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 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>