Next / Previous / Contents / TCC Help System / NM Tech homepage

13.7. A small example: XHTML page generation

Here's a small complete script that generates an XHTML web page. The page we want to build looks like this:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
  "-//W3C//DTD XHTML 1.0 Strict//EN">
<html>
  <head>
    <title>This is the first title.</title>
  </head>
  <body>
    <h1 class='major'>This is the second title.</h1>
    <p id='a37'>This is the first paragraph.<!--Here's a comment.--></p>
  </body>
</html>

The script starts with the usual line to make it self-executing, plus an opening comment and the importation of the xml4create.py module, which we call xc in the script.

xmlcretest
#!/usr/bin/env python
#================================================================
# xmlcretest:  Test driver for xml4create.py
#----------------------------------------------------------------

import xml4create as xc

Before we can create a Document, we need to set up a document type:

xmlcretest
doctype = xc.DocumentType ( "html", "-//W3C//DTD XHTML 1.0 Strict//EN",
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" )

Then, we instantiate the Document using that document type.

xmlcretest
doc  =  xc.Document ( "html", doctype )

Attachment of the page's elements proceeds similarly. The first argument to the Element constructor is the parent element, and the second argument is the new element's name.

xmlcretest
head = xc.Element ( doc.root, "head" )
title = xc.Element ( head, "title" )
body = xc.Element ( doc.root, "body" )

Adding text content to an element is done by passing it as the first argument to the Text constructor:

xmlcretest
xc.Text ( title, "This is the first title." )

Adding attributes to an element can be done by passing keyword arguments to the constructor, like so:

xmlcretest
h1 = xc.Element ( body, "h1", class_='major' )
xc.Text ( h1, "This is the second title." )

You can also add attributes to an element using the syntax for storing into a dictionary:

xmlcretest
p1 = xc.Element ( body, "p" )
p1['id'] = 'a37'
xc.Text ( p1, "This is the first paragraph." )

Adding a comment:

xmlcretest
xc.Comment ( p1, "Here's a comment." )

Finally, write the document to the standard output:

xmlcretest
doc.write()