Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 39 ยท XML, XPath and XSLT

Validating XML with DTD and XML Schema

Learn how DTDs and XML Schema (XSD) define valid XML documents, with element declarations, complex types, occurrence rules, restrictions, and a runnable mini validator.

Well-formed XML only means the syntax is correct. Valid XML also follows a defined vocabulary: which elements may appear, in which order, how often, and with which content. Two languages define that vocabulary: the older DTD and the more powerful XML Schema (XSD). A third, RELAX NG, is mentioned at the end.

DTD

A Document Type Definition is declared inside or alongside the document. It uses its own non-XML syntax.

XML
<!DOCTYPE library [
  <!ELEMENT library (book+)>
  <!ELEMENT book (title, author+, price?)>
  <!ELEMENT title (#PCDATA)>
  <!ELEMENT author (#PCDATA)>
  <!ELEMENT price (#PCDATA)>
  <!ATTLIST book id ID #REQUIRED lang CDATA "en">
]>

Read <!ELEMENT book (title, author+, price?)> as "a book contains a title, then one or more authors, then optionally a price". The occurrence markers:

Marker Meaning
(none) exactly once
? zero or one
* zero or more
+ one or more
a, b sequence: a then b
a | b choice: a or b

#PCDATA means parsed character data (text). <!ATTLIST> declares attributes with types (CDATA, ID, enumerations) and defaults (#REQUIRED, #IMPLIED, a fixed or default value).

DTDs are compact but limited: no namespaces support, no data types beyond a few, and no precise rules such as "a number between 1 and 5". They also bring the entity risks from the previous lesson.

XML Schema (XSD)

An XSD is itself an XML document in the namespace http://www.w3.org/2001/XMLSchema. It adds rich data types, namespaces and reusable type definitions.

XML
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="library">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="book" type="BookType" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="BookType">
    <xs:sequence>
      <xs:element name="title"  type="xs:string"/>
      <xs:element name="author" type="xs:string" maxOccurs="unbounded"/>
      <xs:element name="price"  type="PriceType" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id"   type="xs:ID" use="required"/>
    <xs:attribute name="lang" type="xs:language" default="en"/>
  </xs:complexType>

  <xs:simpleType name="PriceType">
    <xs:restriction base="xs:decimal">
      <xs:minInclusive value="0"/>
      <xs:fractionDigits value="2"/>
    </xs:restriction>
  </xs:simpleType>

</xs:schema>

Key ideas:

  • Simple types describe text-only values: xs:string, xs:integer, xs:decimal, xs:boolean, xs:date, xs:dateTime and so on. A restriction narrows a base type (ranges, patterns, enumerations, lengths).
  • Complex types describe elements with children or attributes. Their content model uses xs:sequence (ordered), xs:choice (one of) and xs:all (any order).
  • minOccurs and maxOccurs (default 1; unbounded for no limit) control repetition.
  • Named types are reusable; anonymous types are declared inline.

A mini validator (stand-in)

A full XSD processor is large. The stand-in below checks a simplified content model: a map of element names to rules for required children, occurrence counts and a simple value type. It illustrates what a validator does, walking the tree and comparing it to the rules.

Node.js Validating against simplified content rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The "bad" document shows a missing required attribute and children in the wrong order, and the extra run shows a value of the wrong type.

Linking a schema to a document

An instance document points to its schema with attributes from the xsi namespace:

XML
<library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="library.xsd">

Validation is performed by a tool or library (xmllint --schema library.xsd doc.xml, Java's javax.xml.validation, Python's lxml), not by the document itself.

Comparing DTD, XSD and RELAX NG

DTD XSD RELAX NG
Syntax its own XML XML or compact text
Data types few rich, extensible borrows XSD types
Namespaces no yes yes
Complexity low high medium

Choose XSD when you need data types and tool support (SOAP, enterprise integrations), RELAX NG when you want readable grammars, and DTD only when a standard you must follow already uses it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does well-formed mean compared with valid?

    Syntax rules versus conformance to a defined vocabulary.
  2. 2. In a DTD, what does author+ mean?

    The plus marker means one or more occurrences.
  3. 3. Which is an advantage of XSD over DTD?

    XSD defines types such as integers and dates, and supports namespaces.
  4. 4. What does xs:sequence mean in a complex type?

    sequence enforces order; choice and all provide the other models.

Summary

  • Well-formed is syntax; valid means conforming to a DTD, XSD or RELAX NG schema.
  • DTDs are compact but untyped; XSD adds data types, namespaces and reusable types.
  • minOccurs, maxOccurs, sequence, choice and restrictions describe content.
  • A validator walks the tree comparing it with the rules; use a real library for XSD.

Next: XPath basics