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'?>
  "-//W3C//DTD XHTML 1.0 Strict//EN">
    <title>This is the first title.</title>
    <h1 class='major'>This is the second title.</h1>
    <p id='a37'>This is the first paragraph.<!--Here's a comment.--></p>

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

#!/usr/bin/env python
# xmlcretest:  Test driver for

import xml4create as xc

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

doctype = xc.DocumentType ( "html", "-//W3C//DTD XHTML 1.0 Strict//EN",
              "" )

Then, we instantiate the Document using that document type.

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.

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:

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:

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:

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

Adding a comment:

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

Finally, write the document to the standard output: