XSD をどのように使用するか?

XML 文書は DTD または XML Schema を参照できます。

シンプルな XML 文書:

以下は "note.xml" という名前の XML 文書です:

<?xml version="1.0"?>
<note>
<to>George</to>
<from>John</from>
<heading>リマインダー</heading>
<body>ミーティングを忘れないように!</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)>

note 元素有四个子元素:"to, from, heading, body" が定義されています。

第 2-5 行では、to、from、heading、body要素のタイプが"#PCDATA"と定義されています。

XMLスキーマ

以下の例は、"note.xsd"という名前のXML Schemaファイルです。このファイルは、上記のXMLドキュメントの要素を定義しています:

<?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要素は複合型です。なぜなら、他の子要素を含んでいるからです。他の要素(to、from、heading、body)は簡易型です。なぜなら、他の要素を含んでいないからです。複合型と簡易型に関する知識を、以下の章で学びます。

DTDの参照

このファイルには、DTDの参照が含まれています:

<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "http://www.codew3c.com/dtd/note.dtd">
<note>
<to>George</to>
<from>John</from>
<heading>リマインダー</heading>
<body>ミーティングを忘れないように!</body>
</note>

XML Schemaの参照

このファイルには、XML Schemaの参照が含まれています:

<?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>リマインダー</heading>
<body>ミーティングを忘れないように!</body>
</note>