كيفية استخدام XSD؟

وثيقة XML يمكن أن تشير إلى DTD أو XML Schema.

مثال بسيط على وثيقة XML:

انظر إلى وثيقة XML المسمى "note.xml":

<?xml version="1.0"?>
<note>
<to>George</to>
<from>John</from>
<heading>تذكير</heading>
<body>لا تنسى الاجتماع!</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" في السطر 1.

تعريف الأنواع للعناصر to, from, heading, body هي "#PCDATA" في الأسطر 2-5.

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>تذكير</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>