3.2. XML Validation Using Schema

Schema is the W3C standard for validating the structure and validity of XML documents. Creating a schema for your XML allows you to specify the structure of the document as a whole, as well as some data types for individual elements. Listing 3-1 shows a sample XML Schema document.

Example 3.1. A Sample XML Schema Document
<xsd:schema xmlns:xsd="http://www.w3.org/2000/08/XMLSchema">
  <xsd:annotation>
    <xsd:documentation>
      Sample Newsletter schema
    </xsd:documentation>
  </xsd:annotation>

  <xsd:element name="my_newsletter" type="NewsletterType"/>

  <xsd:element name="comment" type="xsd:string"/>

  <xsd:complexType name="NewsletterType">
    <xsd:sequence>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="header" type="HeaderType"/>
      <xsd:element name="section1" type="SectionType"/>
      <xsd:element name="section2" type="SectionType"/>
    </xsd:sequence>
    <xsd:attribute name="volume" type="xsd:positiveInteger"/>
    <xsd:attribute name="number" type="xsd:positiveInteger"/>
  </xsd:complexType>

  <xsd:complexType name="HeaderType">
    <xsd:sequence>
      <xsd:element name="long_title" type="xsd:string"/>
      <xsd:element name="filename" type="xsd:string"/>
      <xsd:element name="date" type="xsd:date"/>
      <xsd:element name="meta_title" type="xsd:string"/>
      <xsd:element name="meta_description" type="xsd:string"/>
      <xsd:element name="meta_keywords" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
<xsd:complexType name="SectionType"> <xsd:sequence> <!-- every section must have a title ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.