如何使用 XSD?

Il documento XML può fare riferimento a DTD o XML Schema.

Un documento XML semplice:

Ecco il documento XML chiamato "note.xml":

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

File DTD

Ecco un esempio di file DTD chiamato "note.dtd", che definisce gli elementi del documento XML precedente:

<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

La definizione del elemento note ha quattro sotto-elementi: "to, from, heading, body".

Le righe 2-5 definiscono il tipo degli elementi to, from, heading, body come "#PCDATA".

Schema XML

Esempio: questo file XML Schema denominato "note.xsd" definisce gli elementi del documento XML sopra riportato:

<?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>

L'elemento "note" è di tipo complesso perché contiene altri elementi figli. Gli altri elementi (to, from, heading, body) sono di tipo semplice perché non contengono altri elementi. Apprenderai di più sui tipi complessi e semplici nei capitoli seguenti.

Riferimenti a DTD

Questo file contiene riferimenti a 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>

Riferimenti a XML Schema

Questo file contiene riferimenti a 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>