DTD - DTD Examples

 Basic DTD for a Book

DTD:

<!DOCTYPE book [
  <!ELEMENT book (title, author, price)>
  <!ELEMENT title (#PCDATA)>
  <!ELEMENT author (#PCDATA)>
  <!ELEMENT price (#PCDATA)>
]>

XML using it:

<book>
  <title>Learn XML</title>
  <author>John Doe</author>
  <price>25.00</price>
</book>

This DTD says that a <book> must have exactly these three elements in this order: title, author, and price.


 DTD with attributes

DTD:

<!DOCTYPE student [
  <!ELEMENT student (name, grade)>
  <!ATTLIST student rollNumber CDATA #REQUIRED>
  <!ELEMENT name (#PCDATA)>
  <!ELEMENT grade (#PCDATA)>
]>

XML using it:

<student rollNumber="101">
  <name>Alice</name>
  <grade>A</grade>
</student>

This says the <student> element must have:

  • a rollNumber attribute (which is required)

  • the elements name and grade inside it.


DTD with repeating elements

DTD:

<!DOCTYPE classroom [
  <!ELEMENT classroom (student+)>
  <!ELEMENT student (name, grade)>
  <!ELEMENT name (#PCDATA)>
  <!ELEMENT grade (#PCDATA)>
]>

XML using it:

<classroom>
  <student>
    <name>Bob</name>
    <grade>B</grade>
  </student>
  <student>
    <name>Mary</name>
    <grade>A</grade>
  </student>
</classroom>

 Notice the student+ in the DTD, which means one or more student elements are allowed inside the classroom.


 DTD with choices

DTD:

<!DOCTYPE payment [
  <!ELEMENT payment (cash | creditcard)>
  <!ELEMENT cash (#PCDATA)>
  <!ELEMENT creditcard (#PCDATA)>
]>

XML using it (either one is valid):

<payment>
  <cash>Paid in cash</cash>
</payment>

OR

<payment>
  <creditcard>Visa</creditcard>
</payment>

The | means either cash or creditcard, but not both.