← Back to list

XML, DTD and XML Schema — A FAST Introduction

Feel like brushing up quickly on the important basics in XML, DTD and XML Schema? Here is a quick recap which goes over the details under…

Annie Chakraborty · 2025-07-30 00:27 · 0 claps · 4.7 min read
#xml #xml-schema #dtd #quick-reads #technology
Open on Medium ↗

XML, DTD and XML Schema — A FAST Introduction

Feel like brushing up quickly on the important basics in XML, DTD and XML Schema? Here is a quick recap which goes over the details under just 5 minutes.

Photo by Volodymyr Dobrovolskyy on Unsplash

Photo by Volodymyr Dobrovolskyy on Unsplash

XML (eXtensible Markup Language)

What is XML?

XML is a markup language designed to store and transport data. Unlike HTML (which is about displaying data), XML focuses on data structure and meaning. It is self-descriptive, i.e. it uses self defined tags which describe the data.

Basic Structure

An XML document has the following basic structure: Prolog (optional) — XML declaration Root element — a single top-level element Nested child elements — elements inside elements Attributes and text values

Example:

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book id="b1">
        <title>XML Guide</title>
        <author>John Doe</author>
        <price>29.99</price>
    </book>
</library>

Rules (Grammar of XML)

  1. Well-formedness: Every XML document must be well-formed. XML is well formed when: Only one root element. All tags must be properly nested.
  2. Tags are case-sensitive (<Book><book>).
  3. All tags must be closed (either <tag>content</tag> or self-closing <tag/>).
  4. Attribute values must be quoted (" " or ' ').
  5. No overlapping tags: ❌ <b><i>text</b></i><b><i>text</i></b>
  6. Encoding Declaration: <?xml version=”1.0" encoding=”UTF-8"?> version is mandatory (1.0 or 1.1) encoding is optional but recommended
  7. Special Characters must be escaped: &&amp; < → `&lt;

    &gt; "&quot; '&apos;`

  8. Comments:
<!-- This is a comment -->

Attributes vs Elements

  • Attributes store metadata.
  • Elements store data. Example: <book id="b1"> <title>XML Guide</title> </book>
  • id is attribute (metadata about book).
  • title is element (main data).

Validation

  • An XML is valid when it is well formed and follows a defined grammar (for example, DTD, XMLSchema etc.)

DTD (Document Type Definition)

What is DTD?

DTDs are used to define the structure (grammar) of an XML document. They can be internal (defined inside XML) or external (defined in a separate file).

DTDs specify the elements and their order, and the attributes used in the elements

DTD Syntax

Internal DTD: These are written directly into the XML file as shown below. They can only be used within the XML file they are defined.

<!DOCTYPE library [
    <!ELEMENT library (book+)>
    <!ELEMENT book (title, author, price)>
    <!ATTLIST book id ID #REQUIRED>
    <!ELEMENT title (#PCDATA)>
    <!ELEMENT author (#PCDATA)>
    <!ELEMENT price (#PCDATA)>
]>
<library>
    <book id="b1">
        <title>XML Guide</title>
        <author>John Doe</author>
        <price>29.99</price>
    </book>
</library>

External DTD: Consider we create a DTD file called library.dtd:

<!ELEMENT library (book+)> 
<!ELEMENT book (title, author, price)> 
<!ATTLIST book id ID #REQUIRED> 
<!ELEMENT title (#PCDATA)> 
<!ELEMENT author (#PCDATA)> 
<!ELEMENT price (#PCDATA)>

The external DTD is then imported into all the XML file we want to use it on. For this we add the following line:

<!DOCTYPE library SYSTEM "library.dtd">

DTD Rules

Element Declaration: <!ELEMENT element-name content-model>

Content models:

  • EMPTY – no content.
  • ANY – any content.
  • (#PCDATA) – parsed character data (text).
  • (child1, child2) – must appear in order.
  • (child1 | child2) – either-or.
  • + – one or more, * – zero or more, ? – optional.

Example:

<!ELEMENT book (title, author?, price*)>

Attribute Declaration: <!ATTLIST element-name attribute-name attribute-type occurrence>

Data Types:

CDATA : Stands for Character Data and specifies that the attribute can hold any string of text (unparsed character data). Can contain spaces, numbers, letters, special characters (except <, & without escaping).

ID : Attribute value must be unique within the entire XML document. It is used to uniquely identify an element. Each element can have at most one ID attribute.

<!ATTLIST book id ID #REQUIRED>
...
<book id="b1"/> <!-- must be unique -->

IDREF : Signifies that the attribute value must match an existing ID value in the same document. It creates a reference to another element.

<!ATTLIST author bookRef IDREF #REQUIRED>
...
<book id="b1"/>
<author bookRef="b1"/> <!-- must match the book's id -->

IDREFS : Works like IDREF, but allows multiple space-separated references.

<!ATTLIST author bookRefs IDREFS #REQUIRED>
...
<book id="b1"/>
<book id="b2"/>
<author bookRefs="b1 b2"/> <!-- can reference multiple books -->

NMTOKEN : They stand for Name Token. The value must be a valid XML name (like element names), and cannot contain spaces. It must start with a letter or _, and can include letters, digits, -, _, and ..

<!ATTLIST book category NMTOKEN #REQUIRED>
...
<book category="Fiction"/> <!-- valid -->
<book category="Fiction Books"/> <!-- space not allowed -->

NMTOKENS : Like NMTOKEN, but allows multiple space-separated tokens where each token must be a valid NMTOKEN.

<!ATTLIST book categories NMTOKENS #IMPLIED>
...
<book categories="Fiction Bestseller"/>

ENUMERATION: Allows us to define a list of explicit allowed values that the attribute can have. In the following example, ‘ebook’ is the default value.

<!ATTLIST book format (hardcover|paperback|ebook) "ebook">
...
<book format="hardcover"/> <!-- valid -->
<book format="audiobook"/> <!-- invalid -->

Default values for occurrence:

  • #REQUIRED : Ensures that the attribute is present on the element
  • #IMPLIED : The attribute may be absent (optional)
  • #FIXED "value" : Sets a default value to the attribute

Example:

<!ATTLIST book id ID #REQUIRED>

XML Schema (XSD)

What is XSD?

  • XML Schema Definition (XSD) is a more powerful and modern alternative to DTD.
  • Written in XML itself.
  • Supports data types, namespaces, and constraints.

Basic XSD Structure

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="library">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="book" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="title" type="xs:string"/>
              <xs:element name="author" type="xs:string" minOccurs="0"/>
              <xs:element name="price" type="xs:decimal"/>
            </xs:sequence>
            <xs:attribute name="id" type="xs:ID" use="required"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

XSD Rules

  1. Primitive Data Types xs:string, xs:integer, xs:decimal, xs:boolean, xs:date, xs:time, xs:dateTime, xs:ID, etc.
  2. Complex Types: Elements with child elements and/or attributes.
  3. Occurrence Constraints: minOccurs, maxOccurs control repetitions.
<xs:element name="author" minOccurs="0" maxOccurs="5"/>

Restrictions: Restrictions are used in XSD to limit the allowed values of an element or attribute. We first declare a data type (e.g., xs:string, xs:integer, etc.), then restrict it using some defined rules. For example,

<xs:element name="username">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:minLength value="5"/>
      <xs:maxLength value="12"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

✅ Valid: john123 ❌ Invalid: abc (too short)

Some common rules used in restrictions are:

  • minInclusive / maxInclusive (with numbers)
  • minExclusive / maxExclusive
  • minLength / maxLength
  • length
  • pattern (regular expressions)
  • enumeration (specific allowed values)

Enumeration: Enumerations are a type of restriction that limits the value to a specific list. They can be defined for both elements and attributes.

For example, following is an enumeration defined for an element size

<xs:element name="size">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:enumeration value="Small"/>
      <xs:enumeration value="Medium"/>
      <xs:enumeration value="Large"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Following is an enumeration defined for an attribute status.

<xs:attribute name="status">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:enumeration value="active"/>
      <xs:enumeration value="inactive"/>
      <xs:enumeration value="pending"/>
    </xs:restriction>
  </xs:simpleType>
</xs:attribute>

Namespaces: A namespace in XML is a way to uniquely identify elements and attributes, even if they have the same names but come from different vocabularies. It prevents naming conflicts when combining XML documents or schemas from different sources.

<pers:note xmlns:pers="http://example.com/personal">
    <pers:to>John</pers:to>
    <pers:from>Mary</pers:from>
</pers:note>

<ship:note xmlns:ship="http://example.com/shipping">
    <ship:to>Warehouse 3</ship:to>
    <ship:from>Factory 7</ship:from>
</ship:note>

XSD supports multiple namespaces using xmlns. For example, all elements inside <book> now belong to the namespace [http://example.com/library](http://example.com/library)

<lib:book xmlns:lib="http://example.com/library">
    <lib:title>XML Guide</lib:title>
</lib:book>

Prefix lib: explicitly shows which namespace each element belongs to.

Best Practices

  • Always validate XML with a DTD or XSD.
  • Prefer XSD for modern applications (more powerful).
  • Use meaningful element names and attributes.
  • Keep attributes for metadata, elements for data.
  • Avoid mixed content unless necessary.

메타데이터
post_id
f1c60da689ee
slug
xml-dtd-and-xml-schema-a-fast-introduction-f1c60da689ee
url
https://medium.com/@annie.chakraborty/xml-dtd-and-xml-schema-a-fast-introduction-f1c60da689ee
canonical_url
https://medium.com/@annie.chakraborty/xml-dtd-and-xml-schema-a-fast-introduction-f1c60da689ee
author_url
https://medium.com/@annie.chakraborty
status
ok
fetched_at
2026-06-25 07:00:49