แบบใช้ XSD?

เอกสาร XML สามารถอ้างอิง DTD หรือ XML Schema

เอกสาร XML ที่เรียบง่าย

ดูไฟล์ XML ที่มีชื่อว่า "note.xml"

<?xml version="1.0"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

ไฟล์ DTD

ตัวอย่างดังนี้คือไฟล์ DTD ที่มีชื่อว่า "note.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"。

บรรทัดที่ 2-5 กำหนดชนิดของอิเล็มนต์ to, from, heading, body ว่า "#PCDATA"。

XML Schema

ตัวอย่างดังกล่าวคือไฟล์ XML Schema ที่มีชื่อ "note.xsd" ที่กำหนดอิเล็มนต์ของเอกสาร 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>Reminder</heading>
<body>Don't forget the meeting!</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>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>