Here is the explanation of DTD and Schema:
DTD:
DTD, which stands for Document Type Definition, is a formal specification used to define the structure and the legal elements and attributes of an XML document.
• It serves as a schema definition for XML, providing a set of rules that describe the data content and organization within an XML document.
• DTDs are often used to validate the correctness of XML documents and to ensure that they conform to a specific structure.
<!DOCTYPE bookstore [
<!ELEMENT bookstore (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>The DTD above is interpreted like this:
- <!DOCTYPE bookstore– Defines that the root element of the document is bookstore
- <!ELEMENT bookstore– Defines that the bookstore element must contain the elements: “title, author, price”
- <!ELEMENT title– Defines the title element to be of type “#PCDATA“
- <!ELEMENT author– Defines the author element to be of type “#PCDATA“
- <!ELEMENT price– Defines the price element to be of type “#PCDATA“
Types of DTD:
There are two types of DTDs:
- Internal DTD
- External DTD.
Internal DTD:
In an internal DTD, the DTD declarations are included directly within the XML document. The DTD declarations are placed inside the document’s <!DOCTYPE> declaration.
Example of an XML document with an internal DTD:
<!DOCTYPE bookstore [
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>
<bookstore>
<book>
<title>Introduction to XML</title>
<author>John Doe</author>
<price>29.95</price>
</book>
</bookstore>
In this example, the DTD declarations are enclosed within the <!DOCTYPE> declaration before the root element (<bookstore>).
External DTD:
In an external DTD, the DTD declarations are stored in a separate external file and linked to the XML document. The external DTD file is referenced in the <!DOCTYPE> declaration using the SYSTEM keyword.
Example of an XML document with an external DTD:
books.dtd:
<!ELEMENT bookstore (book+)>
<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
books.xml:
<!-- bookstore.xsd -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- Define the elements -->
<xs:element name="bookstore">
<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"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Now, let’s use this XML Schema to validate an XML document:
Discussion 0