如何使用 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)>

ข้อกำหนด note มีสมาชิกลูกสี่อย่างคือ: "to, from, heading, body"。

บรรทัดที่ 2-5 กำหนดชนิดของ element ที่ to, from, heading, body คือ "#PCDATA"

XML Schema

ตัวอย่างดังนี้เป็นไฟล์ XML Schema ที่มีชื่อ "note.xsd" ที่กำหนด element ของเอกสาร 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>

element นี้เป็นชนิด compound ตรงนี้ เพราะมันมี element ลูกอื่น ๆ อีกเช่น (to, from, heading, body) คือชนิด simple เพราะมันไม่มี element ลูกอื่น ๆ คุณจะได้เรียนรู้เกี่ยวกับ compound type และ simple type มากยิ่งขึ้นในบทดังต่อไป

การอ้างอิง 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>