Skip to main content

Well formed XML and DTD example

Short answer

A well-formed XML document follows syntax rules: one root element, proper nesting, matching tags, quoted attributes, and escaped special characters. DTD defines allowed element structure and attributes. Example: <!DOCTYPE book [ <!ELEMENT book (title, author+, price)> with required CDATA attribute isbn, and title, author, price as #PCDATA.

What do you mean by well formed XML document? Explain DTD with example.

Well-formed XML document

A well-formed XML document follows the basic syntax rules of XML, so any XML parser can read it. Rules:

  1. There must be exactly one root element.
  2. Every start tag must have a matching end tag (or be self-closed, <br/>).
  3. Elements must be properly nested (<a><b></b></a>, not <a><b></a></b>).
  4. Tag names are case-sensitive (<Name> is not </name>).
  5. Attribute values must be quoted, and an attribute cannot appear twice in an element.
  6. Special characters must be escaped (&lt;, &gt;, &amp;, &quot;, &apos;).
  7. Names must start with a letter or underscore and contain no spaces.

Well-formed does not mean valid; valid means it also follows a DTD or schema.

DTD (Document Type Definition)

A DTD defines the allowed structure of an XML document: element names, their order and nesting, number of occurrences, and attributes. It can be internal (in the document) or external (a separate .dtd file).

Declarations: <!ELEMENT ...>, <!ATTLIST ...>, <!ENTITY ...>. Content symbols: , sequence, | choice, + one or more, * zero or more, ? optional, #PCDATA text.

Example

<?xml version="1.0"?>
<!DOCTYPE book [
  <!ELEMENT book (title, author+, price)>
  <!ATTLIST book isbn CDATA #REQUIRED>
  <!ELEMENT title  (#PCDATA)>
  <!ELEMENT author (#PCDATA)>
  <!ELEMENT price  (#PCDATA)>
]>
<book isbn="978-0-13-1">
  <title>Web Technology</title>
  <author>A. Sharma</author>
  <author>B. Rai</author>
  <price>650</price>
</book>

Here book must contain one title, one or more author elements and one price, in that order, and must carry the required attribute isbn. Anything else makes the document invalid.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Web Technology chapter 7 questions →