DTD tutorial: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
 
(41 intermediate revisions by the same user not shown)
Line 1: Line 1:
<pageby nominor="false" comments="false"/>
<!-- <pageby nominor="false" comments="false"/> -->
{{web technology tutorial|intermediate}}
{{web technology tutorial|intermediate}}
{{incomplete}}
{{incomplete}}
This should be better coordinated with [[Editing XML tutorial]]. There are too many overlaps ...


== Introduction ==
== Introduction ==
Line 27: Line 25:
'''Next steps'''
'''Next steps'''


* [[XSLT Tutorial - Basics]]
* [[CSS for XML tutorial]] (Styling very text-centric contents)
* [[XML Schema tutorial - Basics]] (alternative schema language)
* [[XSLT Tutorial - Basics]] (Rendering XML contents by translating to HTML)
* [[XPath tutorial - basics]]
* [[XPath tutorial - basics]]
* [[XQuery tutorial - basics]] (if you have interest in XML databases)
* [[XQuery tutorial - basics]] (if you have interest in XML databases)
Line 37: Line 37:


'''DTD grammars are a set of rules that define:'''
'''DTD grammars are a set of rules that define:'''
# a set of '' elements'' (tags) and their '' attributes'' that can be used to create an XML document;
# a set of ''elements'' (tags) and their ''attributes'' that can be used to create an [[XML]] document;
# '' how'' elements can be '' embedded'' ;
# ''how'' these elements can be ''combined/embedded'' ;
# different sorts of entities (reusable fragments, special characters).
# different sorts of entities (reusable fragments, special characters).


DTDs can't define content types, i.e. what text will go inside elements. Most attribute can't be typed either. For example, with a DTD one cannot specify that input should be a number from 0 to 100..
DTDs can't define element content types, i.e. what text can go inside elements. Most attribute can't be typed either. For example, with a DTD one cannot specify that input should be a number from 0 to 100..
 
=== XML Principles recalled ===


'''Specification of a markup language'''
'''Specification of a markup language'''


* The most important part of a DTD-based markup language is usually the DTD itself, but in addition other constraints can be added in a design document!
There are many ways of defining a XML language. You could write down the specification of an XML vocabulary in simple prose, or use a so-called Schema language, or finally, a combination of the two. The most simple schema language, i.e. DTDs, is defined in the XML Standard.
 
'''DTD''' stands for '''Document Type Definition'''. A DTD is a set of rules that constitute a grammar (also called schema) that defines the so-called ''XML application'' also called ''XML vocabular''. For example, the file [http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd xhtml1-transitional.dtd] available at through the [http://www.w3.org/TR/xhtml1/dtds.html XHTML 1.0 specification] page, formally defines the grammar for the [[XHTML]] 1 web markup language.
 
* The most important part of a DTD-based markup language is usually the DTD itself, but in addition other constraints can be added in a design document.
* The DTD does not identify the root element ! You will have to tell the users what elements can be root elements.
* The DTD does not identify the root element ! You will have to tell the users what elements can be root elements.
* Since DTDs can't express data constraints, write them out in a specification document, e.g. "the value of length attribute is a string composed of a number plus "cm" or "inch" or "em". Exemple
* Since DTDs can't express data constraints, write them out in a specification document, e.g. "the value of ''length'' attribute is a string composed of a number plus "cm" or "inch" or "em". Examples:
<source lang="xml">
  <size length="10cm">
  <size length="10cm">
<size length="3inch">
</source>


Example 1: A simple DTD
Example 1: A simple DTD
Line 58: Line 67:
</source>
</source>


A DTD document contains just rules .... nothing else (see later for explanations)
A DTD document contains just rules and no XML declaration is needed ... more details later ...


== Declaring and using a DTD with an XML document ==
=== Associating a DTD with an XML document ===


'''DTD''' stands for '''Document Type Definition'''. A DTD is a set of rules that constitute a grammar (also called schema) that defines the so-called XML application. For example, the file [http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd DTD/xhtml1-transitional.dtd] available at through the [http://www.w3.org/TR/xhtml1/dtds.html XHTML 1.0 specification] formally defines the grammar for the [[XHTML]] language.
Before we learn how to create our own grammars, let's shortly recall how how to associate a DTD with an XML file. For more details, please read the [[Editing XML tutorial]].


Before we learn how to create our own grammars, let's have a look on how to use DTDs.
* In the XML file, you can add a '''declaration that specifies the DTD''' and that implicitly requires that XML contents must be validated.
 
* This DTD file is declared on top of the file after the XML declaration.
=== Document type declarations ===
 
* A '''valid''' XML document usually includes a '''declaration that specifies the DTD'''
* the DTD is declared on top of the file after the XML declaration.
* XML declarations, DTD declaration etc. are part of the prologue
* XML declarations, DTD declaration etc. are part of the prologue


Line 82: Line 87:
</source>
</source>


; There are four ways of using a DTD
Let us recall from the [[editing XML tutorial]], that there are four ways of using a DTD


(1) '''No DTD'''  
(1) '''No DTD'''  
Line 90: Line 95:
* We get a "standalone" document (the XML document is self-sufficient)
* We get a "standalone" document (the XML document is self-sufficient)


(3) "Private/System" DTDs
(3) '''"Private/System" DTDs'''
* the DTD is located on the system (own computer or the Internet). That's what you are going to use when you write your own DTDs.
* As shown in the example above, the DTD is located on the system (own computer or the Internet). That's what you are going to use when you write your own DTDs.
<source lang="xml"> <!DOCTYPE hello SYSTEM "hello.dtd"></source>


(4) Public DTDs,
(4) '''Public DTDs'''
* we use a name for the DTD. This means that both your XML editor and user software know the DTD. This is the strategy used for common Web DTDs like XHTML, SVG, MathML, etc.
* we use a name for the DTD. This means that both your XML editor and user software know the DTD. This is the strategy used for common Web DTDs like XHTML, SVG, MathML, etc.


=== Syntax of the DTD declaration in the XML document ===
Finally, let us recall that other schema formalism than DTDs exist, e.g. [[XML Schema]].
 
A DTD declaration starts with the keyword "DOCTYPE ... followed by the root element:
: Remember that DTDs don't know their root element, root is defined in the XML document ! Also note that DTDs must define this root element just like any other element ! (you can have more than one)
 
<source lang="xml">
  <!DOCTYPE ''hello'' .... >
</source>
 
; ... followed by the DTD definition or a reference to a DTD file as you can see below.
 
There exist a few alternatives
 
; Syntax for internal DTDs
: DTD rules can be inserted within an XML document between brackets [ ... ]
<source lang="xml">
    <!DOCTYPE hello ['
        <!ELEMENT hello (#PCDATA)>
        ]>
</source>
: That technique is very rarely used, since the user will have to copy the DTD lines from one document to another for reusing it.
 
; Syntax to define "private" external DTDs
: Private DTDs are the ones you would create
: The DTD is identified by the URL after the "'' SYSTEM'' " keyword
 
<source lang="xml">
<!DOCTYPE hello '' SYSTEM "hello.dtd"'' >
</source>
 
;Syntax for public DTDs
: Public DTDs are DTDs that are intended for larger use
: After the "'' PUBLIC'' " keyword on has to specify an official name and a backup URL that a validator could use.
: Anyone can create an "official" names, but there exit rules that we will not explain here.
 
<source lang="xml">
<!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN"
  "http://my.netscape.com/publish/formats/rss-0.91.dtd"'' >
</source>


=== Sample XML documents with DTD declarations ===
=== Sample XML documents with DTD declarations ===


;Example 2 - Hello XML without DTD
; Example 1 - Hello XML without DTD


<source lang="xml">
<source lang="xml">
Line 146: Line 112:
</source>
</source>


;Example 3 - Hello XML with an internal DTD
;Example 2 - Hello XML with an internal DTD


<source lang="xml">
<source lang="xml">
Line 157: Line 123:
</source>
</source>


;Example 4 - Hello XML with an external DTD
;Example 3 - Hello XML with an external DTD
: That's what you should with your own home-made DTDs
: That's what you should with your own home-made DTDs


Line 166: Line 132:
</source>
</source>


;Example 5 - XML with a public external DTD (RSS 0.91)
;Example 4 - XML with a public external DTD (RSS 0.91)


<source lang="xml">
<source lang="xml">
  <?xml version="1.0" "?>
  <?xml version="1.0" ?>
  <!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN"
  <!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN"
   "http://my.netscape.com/publish/formats/rss-0.91.dtd">
   "http://my.netscape.com/publish/formats/rss-0.91.dtd">
Line 372: Line 338:
== Definition of elements ==
== Definition of elements ==


Les recall what DTD grammars are supposed to do. DTDs define
Le us recall what DTD grammars are supposed to do. DTDs define
# a set of '' elements'' (tags) and their '' attributes'' that can be used to create an XML document;
# a set of '' elements'' (tags) and their '' attributes'' that can be used to create an XML document;
# and define ''how'' elements can be ''embedded'';
# and define ''how'' elements can be ''embedded'';


In addition, a DTD may define different sorts of entities (reusable fragments, special characters) and attribute types for elements.
In addition, a DTD may define different sorts of entities (reusable fragments) and attribute types for elements. We shall explain the use of attributes and entities below.


'''Syntax of a DTD rule to define elements:
'''Syntax of a DTD rule to define elements:
Line 391: Line 357:


* Mixed contents, i.e. child elements mixed with data (#PCDATA)
* Mixed contents, i.e. child elements mixed with data (#PCDATA)
 
:'''important''': The #PCDATA element must come first !
<source lang="xml">
<source lang="xml">
  <!ELEMENT para (strong | #PCDATA )*>
  <!ELEMENT para (#PCDATA | strong)*>
</source>
</source>
   
   
Line 418: Line 384:
Each tag name must start with a letter or an underscore ('_')<br /> followed by letters, numbers or the following characters: '_' , '-', '.', ':'
Each tag name must start with a letter or an underscore ('_')<br /> followed by letters, numbers or the following characters: '_' , '-', '.', ':'


BAD example:
'''Bad''' examples
  <!ELEMENT 1st ...>
  <!ELEMENT 1st ...>
  <!ELEMENT My Home ...>


BAD example:
'''Good''' examples:
  <!ELEMENT First ...>
   <!ELEMENT My Home ...>
   <!ELEMENT My_Home ...>


=== Combination rules ===
=== Combination rules ===
Line 443: Line 410:
Elements in that order
Elements in that order
| <source lang="xml">
| <source lang="xml">
  <!ELEMENT person ( name ,email? )>
  <!ELEMENT person
  <!ELEMENT Name (First, Middle, Last)>
          ( name ,email? )>
</source>
</source>
| <source lang="xml">
<source lang="xml">
<person>
  <!ELEMENT Name
  <name>Joe</name>
          (First, Middle, Last)>
  <email>x@x.x</email>
</source>
</person>
|<source lang="xml">
<person>
<name>Joe</name>
<email>x@x.x</email>
</person>
</source>
</source>


<source lang="xml">
<source lang="xml">
<Name>
<Name>
  <First>D.</First><Middle>K.</Middle><Last>S.</Last>
<First>D.</First>
</Name></source>
<Middle>K.</Middle>
 
<Last>S.</Last>
</Name>
</source>
|-
|-
| A?
| A?
Line 464: Line 437:
(it can be present or absent)
(it can be present or absent)
|<source lang="xml">
|<source lang="xml">
  <!ELEMENT person (name,  email? )>
  <!ELEMENT person  
  <!ELEMENT Name (First,Middle?,Last)></source>
          (name,  email? )>
</source>
<source lang="xml">
  <!ELEMENT Name
          (First,Middle?,Last)>
</source>
| <source lang="xml">
| <source lang="xml">
  <person>
  <person>
Line 472: Line 450:
</source>
</source>
<source lang="xml">
<source lang="xml">
<Name><First>D.</First><Last>S.</Last></Name>
<Name>
<First>D.</First>
<Last>S.</Last>
</Name>
</source>
</source>
|-
|-
| A
| A+
| At least one A
| At least one A
|<source lang="xml">
|<source lang="xml">
  <!ELEMENT person (name,  email+ )>
  <!ELEMENT person
  <!ELEMENT list (movie+)</source>
          (name,  email+ )>
</source>
<source lang="xml">
  <!ELEMENT list  
          (movie+)
</source>
| <source lang="xml">
| <source lang="xml">
  <person> <name>Joe</name>
  <person> <name>Joe</name>
Line 496: Line 482:
| Zero, one or several A
| Zero, one or several A
| <source lang="xml">
| <source lang="xml">
   <!ELEMENT person (name,  email* )>
   <!ELEMENT person  
   <!ELEMENT list (item*)</source>
          (name,  email* )>
 
</source>
<source lang="xml">
   <!ELEMENT list
            (item*)
</source>
| <source lang="xml">
| <source lang="xml">
<person>
<person>
  <name>Joe</name>
  <name>Joe</name>
  </person></source>
</person>
</source>
<source lang="xml">
<source lang="xml">
   <list>
   <list>
Line 508: Line 499:
   </list></source>
   </list></source>
|-
|-
| A | B
| A <nowiki>|</nowiki> B
| Either A or B
| Either A or B
|<source lang="xml">
|<source lang="xml">
  <!ELEMENT person ( email | fax )>
  <!ELEMENT person  
  <!ELEMENT major (economics | law)></source>
          ( email | fax )>
</source>
<source lang="xml">
  <!ELEMENT major  
          (economics | law)>
</source>
| <source lang="xml">
| <source lang="xml">
<person> <name>Joe</name>
<person> <name>Joe</name>
  <email>x@x.x</email>
  <email>x@x.x</email>
</person>
</person>
<person> <name>Joe</name>
 
  <fax>123456789</fax>
<person> <name>Joe</name>
</person></source>
  <fax>123456789</fax>
</person></source>
<source lang="xml">
<source lang="xml">
<major>  
<major>  
   <economics> </economics>
   <economics> </economics>
  </major>     </source>
  /major>
</source>
|-
|-
| (A, B)
| (A, B)
| Parenthesis will group and you can apply the above combination rules to the whole group
| Parenthesis will group and you can  
apply the above combination rules to the whole group
| <source lang="xml">
| <source lang="xml">
   <!ELEMENT text (para | list | title)*></source>
   <!ELEMENT text  
| <source lang="xml">
            (para | list | title)*>
  <text>
</source>
    <title>Story</title>
|<source lang="xml">
    <para>Once upon a time</para>  
<text>
    <title>The awakening</title>  
<title>Story</title>
    <list> ... </list>
<para>Once upon a time</para>  
</text>
<title>The awakening</title>  
<list> ... </list>
</text>
</source>
</source>
|}
|}
Line 541: Line 542:
=== Contents of DTD elements ===
=== Contents of DTD elements ===


Inside an element we either can find child elements only, data only or mixed data plus elements, and finally nothing.
As explained above, DTDs allow to define four different kinds of XML elements with respect to their content. XML elements can either include just other elements, just data (no elements), so-called mixed contents, or no data. We illustrate this with examples:


Examples
'''(1) Child elements only'''
* Child elements only:
<source lang="xml">
<source lang="xml">
<ul><li></li><li></li><li></li></ul></source>
<ul>
* Data only:
<li>Item 1</li>
<li>Item 2</li><li>Item 3</li>
</ul>
</source>
 
'''(2) Data only'''
<source lang="xml">
<source lang="xml">
<para>Here we go</para></source>
<para>Here we go</para></source>
* Mixed data:
 
'''(3) Mixed contents, i.e. both data and elements
<source lang="xml">
<source lang="xml">
<para>Here we go <bold>fast</bold></para></source>
<para>Here we go <bold>fast</bold></para></source>
* Empty:
 
<source lang="xml"><newline/></source>
'''(4) Empty elements'''
<source lang="xml">
<newline/>
</source>
 
The following table summarizes how DTDs allow to define element contents other than combinations of child elements.


{| class="wikitable"   
{| class="wikitable"   
Line 592: Line 603:
  <para> here is a <a href="xx">link</a>. <b>Check</b> it out </para></source>
  <para> here is a <a href="xx">link</a>. <b>Check</b> it out </para></source>


To allow for these mixed contents, one '''must use''' the "|" construct as shown in the good examples below.
To allow for these mixed contents, one '''must''' , as shown in the good examples below.
*  use the "|" construct for listing the alternatives
*  Make it repeatable using the (....)* construct.
*  specify #PCDATA first


;Good examples:
;Good examples:
Line 607: Line 621:
<source lang="xml">
<source lang="xml">
  <!ELEMENT p (name, first_name, #PCDATA)*>
  <!ELEMENT p (name, first_name, #PCDATA)*>
<!ELEMENT p (name | first_name | #PCDATA)*>  <!-- #PCDATA is not first -->
  <!ELEMENT p ( (#PCDATA) |a|ul|b|i|em)*>
  <!ELEMENT p ( (#PCDATA) |a|ul|b|i|em)*>
</source>
</source>
Line 632: Line 647:
</source>
</source>


The we must provide and '''attibute type''' with a keyword. There exist six types: normal text, single words, an ID, a (or more) reference(s) to an ID of another attribute, and a list of values. These types are summarized in the followin table.
We then must provide an '''attribute type''' using a keyword. There exist six attribute types: '''normal text''', '''single word''', an ''ID'', a (or more) '''reference(s) to an ID''' of another attribute, and a '''list of values'''. These types are summarized in the following table.


{| class="wikitable"   
{| class="wikitable"   
Line 653: Line 668:
| Reference to one or more identifiers
| Reference to one or more identifiers
|-
|-
| (A|B|C|..)
| <nowiki>(A|B|C|..)</nowiki>
| List of values (from which the user must choose)
| List of values (from which the user must choose)
|}
|}
Finally, we have to decide whether an attribute is mandatory, optional or fixed.
Finally, we have to decide whether an attribute is mandatory, optional or fixed.


Line 678: Line 694:
! example XML
! example XML
|-
|-
| <!ATTLIST person first_name CDATA #REQUIRED>
| <source lang="XML"><!ATTLIST person first_name CDATA #REQUIRED></source>
| <person first_name="Joe">
| <person first_name="Joe">
|-
|-
| <!ATTLIST person gender (male|female) #IMPLIED>
| <source lang="XML"><!ATTLIST person gender (male|female) #IMPLIED></source>
| <person gender="male">
| <person gender="male">
|-
|-
| <!ATTLIST form method CDATA #FIXED "POST">
| <source lang="XML"><!ATTLIST form method CDATA #FIXED "POST"></source>
| <form method="POST">
| <form method="POST">
|-
|-
| <!ATTLIST list type (bullets|ordered) "ordered">
| <source lang="XML"><!ATTLIST list type (bullets|ordered) "ordered"></source>
| <list type="bullets">
| <list type="bullets">
|-
|-
| <!ATTLIST sibling type (brother|sister) #REQUIRED>
| <source lang="XML"><!ATTLIST sibling type (brother|sister) #REQUIRED></source>
| <sibling type="brother">
| <sibling type="brother">
|-
|-
| <!ATTLIST person id ID #REQUIRED>
| <source lang="XML"><!ATTLIST person id ID #REQUIRED></source>
| <person id="N1004">
| <person id="N1004">
|}
|}
Line 699: Line 715:
=== Shortcut to define multiple attributes for an element: ===
=== Shortcut to define multiple attributes for an element: ===


<!ATTLIST target_tag
Instead of defining each attribute with a different instruction, you can define all attributes for an element with a single one.
<source lang="xml">
<!ATTLIST target_tag
           attr1_nom TypeAttribut TypeDef Defaut
           attr1_nom TypeAttribut TypeDef Defaut
           attr2_nom TypeAttribut TypeDef Defaut
           attr2_nom TypeAttribut TypeDef Defaut
  ...>
  ...>
</source>


; Shortcut illustrations:
; Example


<source lang="xml">
<source lang="xml">
  <!ATTLIST person ident ID #REQUIRED  
  <!ATTLIST person ident ID #REQUIRED  
       gender male|female) #IMPLIED
       gender (male|female) #IMPLIED
       nom CDATA #REQUIRED  
       nom CDATA #REQUIRED  
       prenom CDATA #REQUIRED   
       prenom CDATA #REQUIRED   
Line 731: Line 750:
  </family>
  </family>
</source>
</source>
=== ID, IDREF and IDREFS ===
Attributes of type ID, IDREF and IDREFS are checked for validity. That means:
* Each ID value must be unique and start with a letter
* Each IDREF value IDREFS list of values must point to an element with an existing ID value.
Below is an XML (standalone) example that demonstrates use of an ID an IDREF, and an IDREFS attribute in order to create links between persons.
<source lang="XML">
<?xml version = "1.0"?>
<!DOCTYPE Folks [
<!ELEMENT Folks (Person*)>
<!ELEMENT Person (Name,Email?)>
<!ATTLIST Person Pin ID #REQUIRED>
<!ATTLIST Person Friend IDREF #IMPLIED>
<!ATTLIST Person Likes IDREFS #IMPLIED>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT Email (#PCDATA)>
]>
<Folks>
    <Person Pin = "N1">
      <Name>Someone</Name>
    </Person>
    <Person Pin = "N2" Friend = "N1">
      <Name>Someone else</Name>
    </Person>
   
    <Person Pin = "N3" Likes = "N2 N1">
      <Name>Fan</Name>
    </Person>
</Folks>
</source>
Tip: If you want to avoid strong constraints when you create linking elements, just use normal attribute types ....


== Entities ==
== Entities ==
Entities can be defined as reusable fragments that are either substituted in the DTD or the XML.


=== General entities ===
=== General entities ===
Line 738: Line 793:
Consider entities as abbreviations for some other content. An entity must be defined in the DTD and its contents are substituted when encountered in the XML file. Then, recall that XML initially only defines 5 entities and that HTML does many more...
Consider entities as abbreviations for some other content. An entity must be defined in the DTD and its contents are substituted when encountered in the XML file. Then, recall that XML initially only defines 5 entities and that HTML does many more...


* Use the '' &amp;lt; &amp;amp; &amp;gt; &amp;aquot; &amp;apos;'' entities to refer to  <, &amp;, >,"   and   '''
* Use the '' &amp;lt; &amp;amp; &amp;gt; &amp;aquot; &amp;apos;'' entities to refer to  &lt;, &amp;, &gt; ,"and '


Syntax of an internal entity definition:  <!ENTITY entity_name "content">
Syntax of an internal entity definition:   
: <!ENTITY entity_name "content">


Syntax of an external entity definition: <!ENTITY entity_name SYSTEM URI>
Syntax of an external entity definition, i.e. contents are defined in a file:
: <!ENTITY entity_name SYSTEM "URI">


Syntax of using an entity: &amp;entity_name;
Syntax for using an entity in an XML document:
: &amp;entity_name;


;Illustrations of entity definitions
;Illustrations of entity definitions
Line 758: Line 816:
|-
|-
| <!ENTITY space "&amp;#160;">
| <!ENTITY space "&amp;#160;">
| &amp;#160;
| &space;
|  
|
|-
|-
| <!ENTITY copyright "&amp;#xA9;">
| <!ENTITY copyright "&amp;#xA9;">
Line 772: Line 830:
=== Parameter entities ===
=== Parameter entities ===


Most professional DTDs use parameter entities that are used to simplify DTD writing. More complex DTD often use same structures all over. Instead of typing these several times for each element definition, one can use an ENTITY construction like these:
Most professional DTDs use parameter entities that are used to simplify DTD writing since complex DTDs often use same structures all over. Instead of typing these several times for each element definition, one can use an ENTITY construction like these:


<source lang="xml">
<source lang="xml">
Line 779: Line 837:
</source>
</source>


'''Example DTD entities to define reusable child elements'''
'''Example DTD entities defining reusable child elements'''


<source lang="xml">
<source lang="xml">
Line 785: Line 843:
</source>
</source>


Later in the DTD we then can have element definitions like this:
Later in the DTD we then can build element definitions like this:


<source lang="xml">
<source lang="xml">
Line 792: Line 850:
</source>
</source>


The XML parser will then simply translate these %Content; and we get:
The XML parser will then simply substitute these ''%Content;'' symbols and we get the following "real" DTD rules:


<source lang="xml">
<source lang="xml">
Line 799: Line 857:
</source>
</source>


'''Example of a DTD entity declration
'''Example of a DTD entity declaration for a list of common attributes'''
 
The example below defines reusable attribute definitions.


<source lang="xml">
<source lang="xml">
Line 850: Line 906:


=== The Itsy Bitsy Teeny Weeny Simple Hypertext DTD ===
=== The Itsy Bitsy Teeny Weeny Simple Hypertext DTD ===
'''ibtwsh.dtd''' is a popular mini XHTML that is used to "fill in" child elements of a semantically structured DTD. Here we present a slightly modified version.
'''ibtwsh.dtd''' is a popular mini XHTML that is used to "fill in" child elements of a semantically structured DTD. Here we present a slightly modified version that we used for DTDs to support project-oriented teaching as shown in the examples further down.
* [http://tecfa.unige.ch/guides/xml/examples/dtd-examples/ePBL11/ibtwsh6_ePBL.dtd http://tecfa.unige.ch/guides/xml/examples/dtd-examples/ePBL11/ibtwsh6_ePBL.dtd]
* [http://tecfa.unige.ch/guides/xml/examples/dtd-examples/ePBL11/ibtwsh6_ePBL.dtd http://tecfa.unige.ch/guides/xml/examples/dtd-examples/ePBL11/ibtwsh6_ePBL.dtd]
that we used in project-oriented teaching.


<source lang="xml">
<source lang="xml">
Line 1,196: Line 1,251:


<!--  _______________________ MAIN ELEMENT  _______________________ -->
<!--  _______________________ MAIN ELEMENT  _______________________ -->
<!ELEMENT project  (name, authors, date, updated, goal, state-of-the-art, research-development-questions, methodology, workpackages ) >
<!ELEMENT project  (name, authors, date, updated, goal, state-of-the-art,
                    research-development-questions, methodology, workpackages ) >


<!ELEMENT name  (#PCDATA )>
<!ELEMENT name  (#PCDATA )>
Line 1,313: Line 1,369:


* Each element needs to be defined, but only once !
* Each element needs to be defined, but only once !
* Only make elements mandatory if they really are wanted, else use e.g. element ?
* Only make elements mandatory if they really are wanted, i.e. make the others optional, e.g. by using the "?" as in ''element?''


; Plan the global structure
; Plan the global structure

Latest revision as of 14:52, 21 January 2020

Introduction

This is a short tutorial about creating simple DTDs (Document Type Definitions).

Learning goals

  • Be able to read a DTD
  • Be able to create a simple DTD with nested elements, i.e. understand combination features
  • Be able to define attributes for elements
  • Know how to create and use DTD entities

Prerequisites

Next steps

Executive overview

DTD grammars are a set of rules that define:

  1. a set of elements (tags) and their attributes that can be used to create an XML document;
  2. how these elements can be combined/embedded ;
  3. different sorts of entities (reusable fragments, special characters).

DTDs can't define element content types, i.e. what text can go inside elements. Most attribute can't be typed either. For example, with a DTD one cannot specify that input should be a number from 0 to 100..

XML Principles recalled

Specification of a markup language

There are many ways of defining a XML language. You could write down the specification of an XML vocabulary in simple prose, or use a so-called Schema language, or finally, a combination of the two. The most simple schema language, i.e. DTDs, is defined in the XML Standard.

DTD stands for Document Type Definition. A DTD is a set of rules that constitute a grammar (also called schema) that defines the so-called XML application also called XML vocabular. For example, the file xhtml1-transitional.dtd available at through the XHTML 1.0 specification page, formally defines the grammar for the XHTML 1 web markup language.

  • The most important part of a DTD-based markup language is usually the DTD itself, but in addition other constraints can be added in a design document.
  • The DTD does not identify the root element ! You will have to tell the users what elements can be root elements.
  • Since DTDs can't express data constraints, write them out in a specification document, e.g. "the value of length attribute is a string composed of a number plus "cm" or "inch" or "em". Examples:
 <size length="10cm">
 <size length="3inch">

Example 1: A simple DTD

 <!ELEMENT page  (title, content, comment?)>
 <!ELEMENT title (#PCDATA)>
 <!ELEMENT content (#PCDATA)>
 <!ELEMENT comment (#PCDATA)>

A DTD document contains just rules and no XML declaration is needed ... more details later ...

Associating a DTD with an XML document

Before we learn how to create our own grammars, let's shortly recall how how to associate a DTD with an XML file. For more details, please read the Editing XML tutorial.

  • In the XML file, you can add a declaration that specifies the DTD and that implicitly requires that XML contents must be validated.
  • This DTD file is declared on top of the file after the XML declaration.
  • XML declarations, DTD declaration etc. are part of the prologue
Example XML contents with a DTD declaration
 <?xml version="1.0" ?>
 <!DOCTYPE hello SYSTEM "hello.dtd">

 <hello>Here we <strong>go</strong> ... </hello>

Let us recall from the editing XML tutorial, that there are four ways of using a DTD

(1) No DTD

  • XML document will just be well-formed, or validation takes place in some other contexts, e.g. there exist tools that allow you to find out if a given XML document is valid with respect to a given DTD file)

(2) DTD rules are defined inside the XML document

  • We get a "standalone" document (the XML document is self-sufficient)

(3) "Private/System" DTDs

  • As shown in the example above, the DTD is located on the system (own computer or the Internet). That's what you are going to use when you write your own DTDs.

(4) Public DTDs

  • we use a name for the DTD. This means that both your XML editor and user software know the DTD. This is the strategy used for common Web DTDs like XHTML, SVG, MathML, etc.

Finally, let us recall that other schema formalism than DTDs exist, e.g. XML Schema.

Sample XML documents with DTD declarations

Example 1 - Hello XML without DTD
 <?xml version="1.0" standalone="yes"?>
 <hello> Hello XML et hello cher lecteur ! </hello>
Example 2 - Hello XML with an internal DTD
  <?xml version="1.0" standalone="yes"?>
  <!DOCTYPE hello [
     <!ELEMENT hello (#PCDATA)>
     ]>

  <hello> Hello XML et hello dear readers ! </hello>
Example 3 - Hello XML with an external DTD
That's what you should with your own home-made DTDs
 <?xml version="1.0" ?>
 <!DOCTYPE hello SYSTEM "hello.dtd">
 <hello> This is a very simple XML document </hello>
Example 4 - XML with a public external DTD (RSS 0.91)
 <?xml version="1.0" ?>
 <!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN"
  "http://my.netscape.com/publish/formats/rss-0.91.dtd">
 <rss version="0.91">
 <channel> ...... </channel>
 </rss>

Understanding DTDs by example

Recall that DTDs define all the elements and attributes and the way they can be combined

Example 6: Hello text with XML

A simple XML document of type <page>
 <?xml version="1.0"?>
 <page>
  <title>Hello friend</title>
  <content>Here is some content :)</content>
  <comment>Written by DKS/Tecfa, adapted from S.M./the Cocoon samples</comment>
 </page>
A DTD that would validate this "page" document

Xml-intro-edit-6.png

Example 7: A recipe list in XML

  • Source: Introduction to XML by Jay Greenspan (now dead URL)
  <?xml version="1.0"?>
  <!DOCTYPE list SYSTEM "simple_recipe.dtd">
  <list>
  <recipe>
    <author>Carol Schmidt</author>
    <recipe_name>Chocolate Chip Bars</recipe_name>
    <meal>Dinner</meal>
    <ingredients>
      <item>2/3 C butter</item>      <item>2 C brown sugar</item>
      <item>1 tsp vanilla</item>     <item>1 3/4 C unsifted all-purpose flour</item>
      <item>1 1/2 tsp baking powder</item>
      <item>1/2 tsp salt</item>      <item>3 eggs</item>
      <item>1/2 C chopped nuts</item>
      <item>2 cups (12-oz pkg.) semi-sweet choc. chips</item>
    </ingredients>
    <directions>
 Preheat oven to 350 degrees. 
 Melt butter; combine with brown sugar and vanilla in large mixing bowl. 
 Set aside to cool. Combine flour, baking powder, and salt; set aside. 
 Add eggs to cooled sugar mixture; beat well. 
 Stir in reserved dry ingredients, nuts, and chips. 
 Spread in greased 13-by-9-inch pan.
 Bake for 25 to 30 minutes until golden brown; cool.  Cut into squares.
    </directions>
  </recipe>
 </list>
Contents of the DTD

Xml-intro-edit-7.png

Example 8: A simple story grammar

 <?xml version="1.0" "?>
 <!-- DTD to write simple stories
      Made by Daniel K. Schneider / TECFA / University of Geneva
      VERSION 1.0
      30/10/2003 -->
 <!ELEMENT STORY (title, context, problem, goal, THREADS, moral, INFOS)>
 <!ATTLIST STORY xmlns:xlink CDATA #FIXED "http://www.w3.org/1999/xlink">
 <!ELEMENT THREADS (EPISODE+)>
 <!ELEMENT EPISODE (subgoal, ATTEMPT+, result) >
 <!ELEMENT ATTEMPT (action | EPISODE) >
 <!ELEMENT INFOS ( ( date | author | a )* ) >
 <!ELEMENT title (#PCDATA) >
 <!ELEMENT context (#PCDATA) >
 <!ELEMENT problem (#PCDATA) >
 <!ELEMENT goal (#PCDATA) >
 <!ELEMENT subgoal (#PCDATA) >
 <!ELEMENT result (#PCDATA) >
 <!ELEMENT moral (#PCDATA) >
 <!ELEMENT action (#PCDATA) >
 <!ELEMENT date (#PCDATA) >
 <!ELEMENT author (#PCDATA) >
 <!ELEMENT a (#PCDATA)>
 <!ATTLIST a
      xlink:href CDATA #REQUIRED
      xlink:type CDATA #FIXED "simple">
Here is a valid skeleton
  <?xml version="1.0" " ?>
  <!DOCTYPE STORY SYSTEM "story-grammar.dtd">
  <?xml-stylesheet href="story-grammar.css" type="text/css"?>
  <STORY>
   <title>The little XMLer</title>
   <context></context>
  <problem></problem>
  <goal></goal>
  <THREADS>
    <EPISODE>
      <subgoal>I have to do it ...</subgoal>
      <ATTEMPT>
        <action></action>
      </ATTEMPT>
      <result></result>
    </EPISODE>
  </THREADS>
  <moral></moral>
  <INFOS>
  </INFOS>
 </STORY>

The picture gives some extra information

Xml-intro-edit-8.png

Example 9: Lone family DTD

Xml-intro-edit-9.png

A valid XML file
 <?xml version="1.0" ?>
 <!DOCTYPE family SYSTEM "family.dtd">
 <family>
   <person name="Joe Miller" gender="male"
           type="father" id="123.456.789"/>
   <person name="Josette Miller" gender="female"
           type="girl" id="123.456.987"/>
 </family>

Example 10: RSS

  • There are several RSS standards. RSS 0.91 is Netscape's original (still being used)
 <!ELEMENT rss (channel)>
 <!ATTLIST rss version CDATA #REQUIRED>
  <!-- must be "0.91"> -->
  <!ELEMENT channel (title | description | link | language | item  | rating? | image? | textinput? | 
               copyright? | pubDate? | lastBuildDate? | docs? | managingEditor? | 
               webMaster? | skipHours? | skipDays?)*>
  <!ELEMENT title (#PCDATA)>
  <!ELEMENT description (#PCDATA)>
  <!ELEMENT link (#PCDATA)>
  <!ELEMENT image (title | url | link | width? | height? | description?)*>
  <!ELEMENT url (#PCDATA)>
  <!ELEMENT item (title | link | description)*>
  <!ELEMENT textinput (title | description | name | link)*>
  <!ELEMENT name (#PCDATA)>
  <!ELEMENT rating (#PCDATA)>
  <!ELEMENT language (#PCDATA)>
  <!ELEMENT width (#PCDATA)>
  <!ELEMENT height (#PCDATA)>
  <!ELEMENT copyright (#PCDATA)>
  <!ELEMENT pubDate (#PCDATA)>
  <!ELEMENT lastBuildDate (#PCDATA)>
  <!ELEMENT docs (#PCDATA)>
  <!ELEMENT managingEditor (#PCDATA)>
  <!ELEMENT webMaster (#PCDATA)>
  <!ELEMENT hour (#PCDATA)>
  <!ELEMENT day (#PCDATA)>
  <!ELEMENT skipHours (hour )>
  <!ELEMENT skipDays (day )>
Possible XML document for RSS
  <?xml version="1.0" " ?>
  <!DOCTYPE rss SYSTEM "rss-0.91.dtd">
  <rss version="0.91">
     <channel>
       <title>Webster University</title>
       <description>Home Page of Webster University</description>
       <link>http://www.webster.edu</link>
       <item>
	 <title>Webster Univ. Geneva</title>
	 <description>Home page of Webster University Geneva</description>
	 <link>http://www.webster.ch</link>
       </item>
       <item>
	 <title>http://www.course.com/</title>
	 <description>You can find Thomson text-books materials (exercise data) on this web site</description>
	 <link>http://www.course.com/</link>
       </item>
     </channel>
   </rss>

Definition of elements

Le us recall what DTD grammars are supposed to do. DTDs define

  1. a set of elements (tags) and their attributes that can be used to create an XML document;
  2. and define how elements can be embedded;

In addition, a DTD may define different sorts of entities (reusable fragments) and attribute types for elements. We shall explain the use of attributes and entities below.

Syntax of a DTD rule to define elements:

 <!ELEMENT tag_name (child_element_specification) >

child_element_specification may contain:

  • A combination of child elements according to combination rules that we will introduce below.
 <!ELEMENT page  (title, content, comment?)>
  • Mixed contents, i.e. child elements mixed with data (#PCDATA)
important: The #PCDATA element must come first !
 <!ELEMENT para (#PCDATA | strong)*>
  • #PCDATA (Just data)
 <!ELEMENT title (#PCDATA)>
  • ANY (only used during development)
 <!ELEMENT para (ANY)*>
  • EMPTY (the element has no contents)
 <!ELEMENT person EMPTY>

Tag names

Each tag name must start with a letter or an underscore ('_')
followed by letters, numbers or the following characters: '_' , '-', '.', ':'

Bad examples

 <!ELEMENT 1st ...>
 <!ELEMENT My Home ...>

Good examples:

 <!ELEMENT First ...>
 <!ELEMENT My_Home ...>

Combination rules

By using the combination rules an information architect (you!) defines how elements can be combined, i.e. mandatory and optional child elements, order of elements, and repetition.

Each and every element in your language must be defined with an <!ELEMENT > rule


A and B = tags Explanation DTD examples XML examples
A , B A followed by B

Elements in that order

 <!ELEMENT person
           ( name ,email? )>
 <!ELEMENT Name
           (First, Middle, Last)>
<person>
 <name>Joe</name>
 <email>x@x.x</email>
</person>
<Name>
 <First>D.</First>
 <Middle>K.</Middle>
 <Last>S.</Last>
</Name>
A? A is optional,

(it can be present or absent)

 <!ELEMENT person 
           (name,  email? )>
 <!ELEMENT Name
           (First,Middle?,Last)>
 <person>
  <name>Joe</name>
</person>
<Name>
 <First>D.</First>
 <Last>S.</Last>
</Name>
A+ At least one A
 <!ELEMENT person
           (name,  email+ )>
 <!ELEMENT list 
           (movie+)
 <person> <name>Joe</name>
   <email>x@x.x</email></person>
 <person> <name>Joe</name>
   <email>x@x.x</email>
   <email>x@y.x</email>
 </person>
 <list>
    <movie>Return of ...</movie>
    <movie>Comeback of ...</movie> 
 </list>
A* Zero, one or several A
  <!ELEMENT person 
           (name,  email* )>
  <!ELEMENT list
            (item*)
<person>
  <name>Joe</name>
</person>
  <list>
   <item>Return of ...</item>
  </list>
A | B Either A or B
 <!ELEMENT person 
          ( email | fax )>
 <!ELEMENT major 
           (economics | law)>
<person> <name>Joe</name>
  <email>x@x.x</email>
</person>

<person> <name>Joe</name>
  <fax>123456789</fax>
</person>
<major> 
   <economics> </economics>
 /major>
(A, B) Parenthesis will group and you can

apply the above combination rules to the whole group

  <!ELEMENT text 
            (para | list | title)*>
<text>
 <title>Story</title>
 <para>Once upon a time</para> 
 <title>The awakening</title> 
 <list> ... </list>
</text>

Contents of DTD elements

As explained above, DTDs allow to define four different kinds of XML elements with respect to their content. XML elements can either include just other elements, just data (no elements), so-called mixed contents, or no data. We illustrate this with examples:

(1) Child elements only

<ul>
 <li>Item 1</li>
 <li>Item 2</li><li>Item 3</li>
</ul>

(2) Data only

<para>Here we go</para>

(3) Mixed contents, i.e. both data and elements

<para>Here we go <bold>fast</bold></para>

(4) Empty elements

 <newline/>

The following table summarizes how DTDs allow to define element contents other than combinations of child elements.

Special elements Explanation DTD examples XML example
#PCDATA "Parsed Character Data"

Text contents of an element. It should not contain any <,>,& etc.

<!ELEMENT email (#PCDATA)>
 <email>Daniel.Schneider@nowhere.org</email>
ANY Allows any non-specified child elements and parsed character data

(avoid this !!!)

<!ELEMENT person ANY>
 <person>
   <c>text</c>
   <a>some <b>bbb</b>inside</a>
 </person>
EMPTY No contents <!ELEMENT br EMTPY> <br/>

Mixed element contents contain both text and tags (elements)

Example:

 <para> here is a <a href="xx">link</a>. <b>Check</b> it out </para>

To allow for these mixed contents, one must , as shown in the good examples below.

  • use the "|" construct for listing the alternatives
  • Make it repeatable using the (....)* construct.
  • specify #PCDATA first
Good examples
 <!ELEMENT para (#PCDATA|a|ul|b|i|em)* >  
 <!ELEMENT p (#PCDATA | a | abbr | acronym | br | cite | code | dfn | em | img | kbd |
           q | samp | span | strong | var )* >  
 <!ELEMENT par (#PCDATA | %font; | %phrase; | %special; | %form;)* >
Bad examples
 <!ELEMENT p (name, first_name, #PCDATA)*>
 <!ELEMENT p (name | first_name | #PCDATA)*>  <!-- #PCDATA is not first -->
 <!ELEMENT p ( (#PCDATA) |a|ul|b|i|em)*>

Defining attributes

Usually an object is defined in terms of its properties and its contents. Translated to XML, objects are usually represented as elements and its properties as attributes. However properties also could be expressed with child elements and the other way round...

Rough syntax of Attribute rules:

<!ATTLIST element_name attr_name Attribute_type Type_Definition Default >

Here are some XML elements with attributes

<img src="picture.png"/>
<person name="Joe Miller" gender="male" type="father" id="N123456789"/>
<a href="http://no.com/bla">no company</a>

When we define such attributes we always start with the same pattern:

 <!ATTLIST name_of_element name_of_attribute ... >

for example

 <!ATTLIST person name ...>

We then must provide an attribute type using a keyword. There exist six attribute types: normal text, single word, an ID, a (or more) reference(s) to an ID of another attribute, and a list of values. These types are summarized in the following table.

Keyword Attribute types
CDATA "Character Data" - Text data
NMTOKEN A single word (no spaces or punctuations)
ID Unique identifier of the element.
IDREF Reference to an identifier.
IDREFS Reference to one or more identifiers
(A|B|C|..) List of values (from which the user must choose)

Finally, we have to decide whether an attribute is mandatory, optional or fixed.

Keyword Type Definition
#IMPLIED Attribute is optional
#REQUIRED Attribute is mandatory
#FIXED Value Attribute has a fixed value (user can't change it)

Below are some illustrations of valid attribute definitions

DTD rule example XML
<!ATTLIST person first_name CDATA #REQUIRED>
<person first_name="Joe">
<!ATTLIST person gender (male|female) #IMPLIED>
<person gender="male">
<!ATTLIST form method CDATA #FIXED "POST">
<form method="POST">
<!ATTLIST list type (bullets|ordered) "ordered">
<list type="bullets">
<!ATTLIST sibling type (brother|sister) #REQUIRED>
<sibling type="brother">
<!ATTLIST person id ID #REQUIRED>
<person id="N1004">

Shortcut to define multiple attributes for an element:

Instead of defining each attribute with a different instruction, you can define all attributes for an element with a single one.

<!ATTLIST target_tag
          attr1_nom TypeAttribut TypeDef Defaut
          attr2_nom TypeAttribut TypeDef Defaut
 ...>
Example
 <!ATTLIST person ident ID #REQUIRED 
      gender (male|female) #IMPLIED
      nom CDATA #REQUIRED 
      prenom CDATA #REQUIRED   
      relation  brother|sister) #REQUIRED >  
 <!ATTLIST portable owner IDREF #REQUIRED >

Example: Lone family DTD (file family.dtd)

Xml-intro-edit-10.png

A valid family XML file
 <?xml version="1.0" ?>
 <!DOCTYPE family SYSTEM "family.dtd">
 <family>
   <person name="Joe Miller" gender="male"
           type="father" id="N123456789"/>
   <person name="Josette Miller" gender="female"
           type="girl" id="N123456987"/>
 </family>

ID, IDREF and IDREFS

Attributes of type ID, IDREF and IDREFS are checked for validity. That means:

  • Each ID value must be unique and start with a letter
  • Each IDREF value IDREFS list of values must point to an element with an existing ID value.

Below is an XML (standalone) example that demonstrates use of an ID an IDREF, and an IDREFS attribute in order to create links between persons.

<?xml version = "1.0"?>
<!DOCTYPE Folks [
	<!ELEMENT Folks (Person*)>
	<!ELEMENT Person (Name,Email?)>
	<!ATTLIST Person Pin ID #REQUIRED>
	<!ATTLIST Person Friend IDREF #IMPLIED>
	<!ATTLIST Person Likes IDREFS #IMPLIED>
	<!ELEMENT Name (#PCDATA)>
	<!ELEMENT Email (#PCDATA)>
	]>
<Folks>
    <Person Pin = "N1">
      <Name>Someone</Name>
    </Person>

    <Person Pin = "N2" Friend = "N1">
      <Name>Someone else</Name>
    </Person>
    
    <Person Pin = "N3" Likes = "N2 N1">
      <Name>Fan</Name>
    </Person>
</Folks>

Tip: If you want to avoid strong constraints when you create linking elements, just use normal attribute types ....

Entities

Entities can be defined as reusable fragments that are either substituted in the DTD or the XML.

General entities

Consider entities as abbreviations for some other content. An entity must be defined in the DTD and its contents are substituted when encountered in the XML file. Then, recall that XML initially only defines 5 entities and that HTML does many more...

  • Use the &lt; &amp; &gt; &aquot; &apos; entities to refer to <, &, > ,", and '

Syntax of an internal entity definition:

<!ENTITY entity_name "content">

Syntax of an external entity definition, i.e. contents are defined in a file:

<!ENTITY entity_name SYSTEM "URI">

Syntax for using an entity in an XML document:

&entity_name;
Illustrations of entity definitions
DTD rule XML example Result
<!ENTITY jt "Joe Test"> <para> &jt; is here<para> <para> Joe Test is here</para>
<!ENTITY space "&#160;"> &space;
<!ENTITY copyright "&#xA9;"> &copyright; D. Schneider © D. Schneider
<!ENTITY explanation SYSTEM "project1a.xml"> <citation> &explanation; </citation> <citation> .... contents of file project1a.xml inserted here ... </citation>

Parameter entities

Most professional DTDs use parameter entities that are used to simplify DTD writing since complex DTDs often use same structures all over. Instead of typing these several times for each element definition, one can use an ENTITY construction like these:

 <!ENTITY  % entity_name "content">
 <!ENTITY  % entity_name SYSTEM "URI">

Example DTD entities defining reusable child elements

 <!ENTITY % Content "(Para | List | Listing)*">

Later in the DTD we then can build element definitions like this:

 <!ELEMENT Intro (Title, %Content; ) >
 <!ELEMENT Goal (Title, %Content; ) >

The XML parser will then simply substitute these %Content; symbols and we get the following "real" DTD rules:

 <!ELEMENT Intro (Title, (Para | List | Listing)*) >
 <!ELEMENT Goal (Title, (Para | List | Listing)* ) >

Example of a DTD entity declaration for a list of common attributes

 <!ENTITY % stamp '
   id ID #IMPLIED
   creation-day NMTOKEN #IMPLIED
   .......
   mod-by NMTOKEN #IMPLIED
   version NMTOKEN #IMPLIED
   status (draft|final|obsolete) #IMPLIED
   approval (ok|not-ok|so-so) #IMPLIED
   main-author CDATA #IMPLIED
   '>

ATTLIST definitions below use %stamp;

 <!ELEMENT main-goal (title, content, (after-thoughts)?, (teacher-comments)?)>
 <!ATTLIST main %stamp; >
 <!ELEMENT title (...)>
 <!ATTLIST main %stamp; >

A complex text-centric example

Use case description

Two DTDs that will help students write research projects and reports. Both include/use a HTML-like DTD to specify formating of element’s contents. Do not worry if you don’t understand all the details, but we believe it’s important to demonstrate in this course some more "real life" examples

We define two DTDs and reuse a third one in both

Each of these DTDs only defines top-level "semantic tags" that define the essential structure of each document type. Elements then contain further markup that is just "stylistic" and taken from the XHTML specification.

In these DTDs we include the ibtwsh6_ePBL DTD as an external entity like this:

<! ENTITY % foreign-dtd SYSTEM "ibtwsh6_ePBL.dtd" >
%foreign-dtd;
For each tag in which we allow stylistic markup, we then can use constructs like:
<!ELEMENT introduction %struct.model;>
<!ELEMENT conclusion %struct.model;>

The Itsy Bitsy Teeny Weeny Simple Hypertext DTD

ibtwsh.dtd is a popular mini XHTML that is used to "fill in" child elements of a semantically structured DTD. Here we present a slightly modified version that we used for DTDs to support project-oriented teaching as shown in the examples further down.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!--
        WARNING: SLIGHTLY MODIFIED FOR USE AT TECFA ! GET THE ORIGINAL
        from http://www.ccil.org/%7Ecowan/XML/ibtwsh6.dtd

	ibtwsh.dtd
	This is the Itsy Bitsy Teeny Weeny Simple Hypertext DTD.
	Its public identifier is -//XML-DEV List//DTD IBTWSH 6.0//EN
	The contents are dedicated to the public domain by
		the author, John Cowan <cowan@ccil.org>, except that
		John Cowan retains the moral right to be known as the author.
	This is draft 6.0
	03/04/2001 Changed by Vivian Synteta 
	Changes: 
	- Correct a mistake (LI)
	- Add IDREF to element "A"
        - Take out id from entity all and IDREFS headers from tables and 
          IDREF from element a 
-->

<!-- 
======================================================================
This is an XML DTD which describes a subset of XHTML Basic for embedded
use within other XML DTDs.  It is by intention equivalent
(within its scope) to -//W3C//DTD XHTML 1.1//EN, but is
not a derived work in the copyright sense.  (Brief excerpts from
HTML 4.0 Transitional appear here and there.)

It is often convenient for XML documents to have a bit of
documentation somewhere in them.  In the absence of a DTD like
this one, that documentation winds up being #PCDATA only, which is
a pity, because rich text adds measurably to the readability of
documents.  By incorporating this DTD by reference (as an
external parameter entity) into another DTD, that DTD inherits
the capabilities of this one.  Using HTML-compatible elements
and attributes allows the documentation to be passed straight
through to HTML renderers.

Current HTML renderers can cope with most XML tags, but empty
tags require special treatment.  Inserting a space before the
terminating "/>" usually makes the "/" (which is not HTML)
invisible.  Using "<tag></tag>" is not as effective, as the
latter is often misinterpreted as a second "<tag>".

Note that since the elements of this DTD are intended to be
used within domain-specific elements of the surrounding DTD,
it is not necessary that every fragment begin with an "html"
element, as in HTML.  Recommended content models for elements
containing documentation are "%horiz.model;" for simple
text fragments and "%struct.model;" for documents in extenso.

Draft 6.0 is seriously incompatible with drafts 5.0 and earlier,
but *is* a subset of XHTML Basic.  I will keep draft 5.0 around;
note that I have changed the FPI.
======================================================================
-->


<!-- =========== Common attributes =========== -->

<!-- All elements (except full-document elements) have these attributes -->
<!ENTITY % all		"id   ID    #IMPLIED
	                ref   IDREF #IMPLIED
		        class CDATA #IMPLIED
			title CDATA #IMPLIED">

<!-- All non-empty elements have these attributes -->
<!ENTITY % i18n		"xml:lang CDATA #IMPLIED
			dir (ltr|rtl) 'ltr'">

<!-- =========== Models =========== -->

<!ENTITY % horiz "#PCDATA | a | abbr | acronym | br | cite | code |
		dfn | em | img | kbd | q | samp | span |
		strong | var">

<!ENTITY % vert "address | blockquote | div | dl | h1 | h2 | h3 |
		ol | p | pre | table | ul">

<!ENTITY % horiz.model "(%horiz;)*">

<!ENTITY % vert.model "(%horiz; | %vert;)*">

<!ENTITY % struct.model "(%vert;)*">


<!-- =========== Horizontal formatting elements =========== -->

<!-- Abbreviations (normal) -->
<!ELEMENT abbr %horiz.model;>
<!ATTLIST abbr %all;>

<!-- Acronyms (normal) -->
<!ELEMENT acronym %horiz.model;>
<!ATTLIST acronym %all;>

<!-- Citation (italics) -->
<!ELEMENT cite %horiz.model;>
<!ATTLIST cite 
	%all;>

<!-- Source code (monowidth) -->
<!ELEMENT code %horiz.model;>
<!ATTLIST code
	%all;>

<!--Terms being defined (normal) -->
<!ELEMENT dfn %horiz.model;>
<!ATTLIST dfn
	%all;>

<!--Emphasis (italics) -->
<!ELEMENT em %horiz.model;>
<!ATTLIST em
	%all;>

<!--Keyboard input -->
<!ELEMENT kbd %horiz.model;>
<!ATTLIST kbd
	%all;>

<!-- Quotation (appropriate quotation marks) -->
<!ELEMENT q %horiz.model;>
<!ATTLIST q
	%all;
	cite CDATA #IMPLIED>

<!-- Sample output text (monowidth) -->
<!ELEMENT samp %horiz.model;>
<!ATTLIST samp
	%all;>

<!-- Arbitrary span of text -->
<!ELEMENT span %horiz.model;>
<!ATTLIST span
	%all;>

<!-- Strong emphasis (boldface) -->
<!ELEMENT strong %horiz.model;>
<!ATTLIST strong
	%all;>

<!-- Variable names (italics) -->
<!ELEMENT var %horiz.model;>
<!ATTLIST var
	%all;>


<!-- IMGs added DKS -->
<!ELEMENT img EMPTY>
<!ATTLIST img
  src     CDATA  #REQUIRED
  alt     CDATA  #IMPLIED
  height  CDATA  #IMPLIED
  width   CDATA  #IMPLIED
  align   CDATA  #IMPLIED
  border  CDATA  #IMPLIED
  hspace  CDATA  #IMPLIED
  vspace  CDATA  #IMPLIED
  %all;>


<!-- Hypertext anchors.
	CONSTRAINT: A elements are not allowed inside
	other A elements, a fact that XML cannot express. -->
<!ELEMENT a %horiz.model;>
<!ATTLIST a
	%all;
	href  CDATA #IMPLIED
	name  CDATA #IMPLIED
	rel   CDATA #IMPLIED
	rev   CDATA #IMPLIED
	target (_BLANK | _TOP | _PARENT) #IMPLIED
>

<!-- Mandatory line breaks -->
<!ELEMENT br EMPTY>
<!ATTLIST br
	%all;>

<!-- =========== Headers =========== -->

<!ELEMENT h1 %horiz.model;>
<!ATTLIST h1
	%all;>

<!ELEMENT h2 %horiz.model;>
<!ATTLIST h2
	%all;>

<!ELEMENT h3 %horiz.model;>
<!ATTLIST h3
	%all;>


<!-- =========== Lists =========== -->

<!-- Definition list -->
<!ELEMENT dl (dt|dd)+>
<!ATTLIST dl
	%all;>

<!-- Defined term -->
<!ELEMENT dt %horiz.model;>
<!ATTLIST dt
	%all;>

<!-- Definition -->
<!ELEMENT dd %horiz.model;>
<!ATTLIST dd
	%all;>

<!-- Ordered list -->
<!ELEMENT ol (li)+>
<!ATTLIST ol
	%all;>

<!-- Unordered list -->
<!ELEMENT ul (li)+>
<!ATTLIST ul
	%all;>

<!-- List element -->
<!ELEMENT li %horiz.model;>
<!ATTLIST li
	%all;>



<!-- =========== Basic table support =========== -->

<!-- Shared attributes -->
<!ENTITY % aligns
	"align (left | center | right | justify) #IMPLIED
	valign (top | middle | bottom | baseline) #IMPLIED">

<!-- Table -->
<!ELEMENT table (caption?, tr+)>
<!ATTLIST table
	%all;
	border      CDATA #IMPLIED
	cellpadding CDATA #IMPLIED
	cellspacing CDATA #IMPLIED
	summary     CDATA #IMPLIED
	width       CDATA #IMPLIED>

<!-- Table caption -->
<!ELEMENT caption %horiz.model;>
<!ATTLIST caption
	%all;>

<!-- Table row -->
<!ELEMENT tr (th | td)+>
<!ATTLIST tr
	%all;
	%aligns;>
	

<!-- Table header -->
<!ELEMENT th %vert.model;>
<!ATTLIST th
	%all;
	%aligns;
	abbr    CDATA #IMPLIED
	axis    CDATA #IMPLIED
	colspan CDATA "1"
	rowspan CDATA "1"
	scope   CDATA #IMPLIED>

<!-- Table data -->
<!ELEMENT td %vert.model;>
<!ATTLIST td
	%all;
	%aligns;
	abbr    CDATA #IMPLIED
	axis    CDATA #IMPLIED
	colspan CDATA "1"
	rowspan CDATA "1"
	scope   CDATA #IMPLIED>


<!-- =========== Other vertical elements =========== -->

<!-- Address block -->
<!ELEMENT address %horiz.model;>
<!ATTLIST address
	%all;>

<!-- Block quotation -->
<!ELEMENT blockquote %struct.model;>
<!ATTLIST blockquote
	%all;
	cite CDATA #IMPLIED>

<!-- General text division -->
<!ELEMENT div %struct.model;>
<!ATTLIST div
	%all;>

<!-- Paragraph -->
<!ELEMENT p %horiz.model;>
<!ATTLIST p
	%all;>

<!-- Preformatted text -->
<!ELEMENT pre %horiz.model;>
<!ATTLIST pre
	%all;>

<!-- =========== END OF ibtwsh.dtd =========== -->

ePBL Project

This DTD allows to define an exploratory student research project and also to keep track of progress by updating certain elements. Other versions were made for projects in experimental psychology.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!-- ___________________________________________ _____________________  -->
<!-- ePBL-project DTD for student project management & specification    -->
<!--   Copyright: (2004) Paraskevi.Synteta@tecfa.unige.ch 	        -->
<!--              http://tecfa.unige.ch/~paraskev/                      -->
<!--                            Daniel K. Schneider             	-->
<!--              http://tecfa.unige.ch/tecfa-people/schneider.html     -->
<!--   Created: 13/11/2002 (based on EVA_pm grammar)     	        -->
<!--   Updated: 07/05/2004					        -->
<!-- VERSIONS							        -->
<!-- v1.1 Adaptations to use with Morphon xml editor and addition of IDs-->
<!-- v1.1b fixed vert.model to struct.model / DKS 2004                  -->
<!-- _________________________________________________________________  -->

<!-- _______________________ ENTITY DECLARATIONS _____________________  -->

<!ENTITY % foreign-dtd SYSTEM "ibtwsh6_ePBL.dtd">
%foreign-dtd;

<!ENTITY % id  "id  ID    #IMPLIED">

<!--  _______________________ MAIN ELEMENT  _______________________ -->
<!ELEMENT project  (name, authors, date, updated, goal, state-of-the-art,
                    research-development-questions, methodology, workpackages ) >

<!ELEMENT name  (#PCDATA )>

<!ELEMENT date (#PCDATA )>

<!ELEMENT authors (#PCDATA )>

<!ELEMENT updated (#PCDATA )>

<!ELEMENT goal (title, description )>

<!ELEMENT state-of-the-art  %struct.model;>
<!ATTLIST state-of-the-art  %id;>

<!ELEMENT research-development-questions (question )+>
<!ELEMENT question (title, description )>

<!ELEMENT methodology  %struct.model;>
<!ATTLIST methodology  %id;>

<!ELEMENT workpackages (workpackage )+>
<!ELEMENT workpackage (planning, objectives, deliverables )>
<!ATTLIST workpackage  %id;>

<!ELEMENT objectives (objective )+>
<!ELEMENT objective (title, description )>

<!ELEMENT deliverables (deliverable )+>
<!ELEMENT deliverable (url, title, description )>
<!ELEMENT url  (#PCDATA )>

<!ELEMENT planning (from, to, hours-of-work?, progress )>
<!ELEMENT from  (#PCDATA )>
<!ELEMENT to  (#PCDATA )>
<!ELEMENT hours-of-work  (#PCDATA )>
<!ELEMENT progress  (#PCDATA )>
<!-- ____________________________________________________________ -->

<!ELEMENT title  (#PCDATA )>
<!ATTLIST title  %id;>

<!ELEMENT description %struct.model;>
<!-- ____________________________________________________________ -->

ePBL paper

We used several versions of this, depending on the nature of the paper we wanted the students to produce.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!-- ___________________________________________ _____________________  -->
<!-- ePBL-paper DTD for student project management & specification      -->
<!--   Copyright: (2004) Paraskevi.Synteta@tecfa.unige.ch 	        -->
<!--              http://tecfa.unige.ch/~paraskev/                      -->
<!--                            Daniel K. Schneider             	-->
<!--              http://tecfa.unige.ch/tecfa-people/schneider.html     -->
<!--   Created: 13/11/2002 (based on EVA_paper grammar)     	        -->
<!--   Updated: 07/05/2004					        -->
<!-- VERSIONS							        -->
<!-- v1.1 Adaptation to use with Morphon xml editor and add IDs, IDREFs -->
<!-- v1.1b fixed vert.model to struct.model / DKS 2004                  -->
<!-- SEE ALSO the book.dtd made by DKS that is simply a superset        -->
<!-- _________________________________________________________________  -->

<!ENTITY % foreign-dtd SYSTEM "ibtwsh6_ePBL.dtd">
<!ENTITY % id  "id  ID    #REQUIRED">

<!-- _________________________ content ________________________________ -->
     
%foreign-dtd;

<!ELEMENT paper ( info, abstract, (preface)?, introduction, main, conclusion, references, (annex)?, (aknowledgements)? ) >

<!ELEMENT info  ( title, authors, date, updated, keywords )>
<!ELEMENT title (#PCDATA )>
<!ELEMENT authors (author )+>
<!ELEMENT author (firstname, familyname, homepageurl, email )>
<!ELEMENT firstname (#PCDATA )>
<!ELEMENT familyname (#PCDATA )>
<!ELEMENT homepageurl (#PCDATA )>
<!ATTLIST homepageurl %all;>
<!ELEMENT email (#PCDATA )>

<!ELEMENT date (#PCDATA )>
<!ELEMENT updated (#PCDATA )>
<!ELEMENT keywords (keyword )+>
<!ELEMENT keyword (#PCDATA )>

<!ELEMENT abstract (#PCDATA )>

<!ELEMENT preface %struct.model;>

<!ELEMENT introduction %struct.model;>

<!ELEMENT main %struct.model;>

<!ELEMENT conclusion %struct.model;>

<!ELEMENT references (reference )+>
<!ELEMENT reference %struct.model;>
<!ATTLIST reference %all;>

<!ELEMENT annex %struct.model;>

<!ELEMENT aknowledgements %struct.model;>

Some advice for designing DTDs

General advice

Don't forget elements and be liberal
  • Each element needs to be defined, but only once !
  • Only make elements mandatory if they really are wanted, i.e. make the others optional, e.g. by using the "?" as in element?
Plan the global structure
  • Before you start writing out DTDs, use some simple "language" to draft the structure, e.g. use a notation like:
name   ==>  family given
family ==> "text"
  • In most cases, each "object" of your "information domain" becomes an element
  • Use child elements to model components
  • Use attributes to describe properties of components
Start from the root element and work your way down
  1. Root element
  2. Child elements of root element
  3. Child elements of the other elements, etc.

Attributes vs. Elements

  • There are some design rules that may help you decide whether using an element or an attribute
  • In case of doubt, always use elements ...
Rather use child elements inside an element to represent an information block
  • if order is important (attributes can't be ordered)
  • if you plan to use the same kind of information block with different parents
  • if a future version of DTD may specify sub-components of an information block
  • if the information block represents a "thing" (an object in OO programming)
  • if the DTD is text-centric, because an author must see contents she/he edits and attributes are often hidden away in XML editors; only use attributes to qualify properties like style !
Rather use attributes to represent an information block
  • if an attribute refers to an other element:
<pet_of owner_name="lisa" pet_type="cat"> would refer to <animal category="cat">
  • to declare usage/type/etc. of an element:
 <address usage="prof"> ... </address>
  • if you wish to list all possible values a user can enter
  • if you want to restrict data type of the attribute value (e.g. require a single word)