Kuinka käyttää XSD:ää?

XML 文档可对 DTD 或 XML Schema 进行引用。

一个简单的 XML 文档:

请看这个名为 "note.xml" 的 XML 文档:

<?xml version="1.0"?>
<note>
<to>George</to>
<from>John</from>
<heading>Muistutus</heading>
<body>Älä unohta kokousta!</body>
</note>

DTD 文件

下面这个例子是名为 "note.dtd" 的 DTD 文件,它对上面那个 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"。

Viersiä 2-5 määrittelee to, from, heading, body-elementtien tyypin "#PCDATA".

XML Schema

Tämä esimerkki on nimeltään "note.xsd" XML Schema -tiedosto, joka määrittelee yllä olevan XML-dokumentin elementit:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.codew3c.com"
xmlns="http://www.codew3c.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-elementti on monimutkainen tyyppi, koska se sisältää muita alielementtejä. Muut elementit (to, from, heading, body) ovat yksinkertaisia tyyppisiä, koska ne eivät sisällä muita elementtejä. Voit oppia lisää monimutkaisista ja yksinkertaisista tyyppityypeistä seuraavissa luvuissa.

Viittaus DTD:hen

Tämä tiedosto sisältää viittauksen DTD:hen:

<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "http://www.codew3c.com/dtd/note.dtd">
<note>
<to>George</to>
<from>John</from>
<heading>Muistutus</heading>
<body>Älä unohta kokousta!</body>
</note>

Viittaus XML Schema:aan

Tämä tiedosto sisältää viittauksen XML Schema:aan:

<?xml version="1.0"?>
<note
xmlns="http://www.codew3c.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.codew3c.com note.xsd">
<to>George</to>
<from>John</from>
<heading>Muistutus</heading>
<body>Älä unohta kokousta!</body>
</note>