Validation
DTD
What is DTD?
DTD defines the legal structure, elements, and attributes of an XML document. It acts as a blueprint to validate the XML document’s format and content.
Types of DTD
Internal DTD: Declared inside the XML document.
External DTD: Declared in a separate file and linked to the XML document.
Basic Syntax
Internal DTD:
<!DOCTYPE rootElement [
<!ELEMENT rootElement (child1, child2)>
<!ELEMENT child1 (#PCDATA)>
<!ELEMENT child2 EMPTY>
<!ATTLIST child1
attributeName CDATA #REQUIRED>
]>
External DTD
<!DOCTYPE rootElement SYSTEM "filename.dtd">
Common DTD Declarations
<!ELEMENT>
Defines an element and its content model (elements, text, empty).
<!ATTLIST>
Defines attributes for elements.
<!ENTITY>
Defines entities (shortcuts for text or special characters).
Example (Internal DTD)
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Alice</to>
<from>Bob</from>
<heading>Reminder</heading>
<body>Meeting at 10 AM</body>
</note>
XML Schema (XSD)
What is XML Schema (XSD)?
XML Schema Definition (XSD) is a more powerful and flexible way to define the structure, content, and data types of an XML document compared to DTD. It supports namespaces, data types, and complex type definitions.
Basic Syntax
Declare schema and define elements
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Key Features
Supports simple types (string, integer, date, etc.) and complex types (elements with nested content).
Allows restriction, extension, and reusability of types.
Validates data types and structure.
Supports namespaces.
Example of Usage in XML Document
<?xml version="1.0" encoding="UTF-8"?>
<note xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="note.xsd">
<to>Alice</to>
<from>Bob</from>
<heading>Reminder</heading>
<body>Meeting at 10 AM</body>
</note>
Advantages over DTD
Data types
No
Yes (string, int, date, etc.)
Namespaces
Limited
Full support
Syntax
Non-XML
XML-based
Extensibility
Limited
Supports complex structures
Last updated