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

13.3. The Element class

Use this class constructor to add elements to your document:

Element ( parent, gi, **attrs )

For the root element of your document, pass the Document object as the parent argument. For all other elements, pass the parent Element object as the first argument.

The gi argument is the qualified name of the element you are creating (also known as the generic identifier). If it begins with a namespace prefix and colon, that namespace prefix must be a key in the document's .nsMap.

You can supply any number of keyword arguments to the constructor, and they will be added as attributes of the new element. For example, if you have an Element object named body, this code would add a new element as its next or only child:

majorHead = Element ( body, "blockquote", align="center" )

and the generated XML would look like this:

  <blockquote align="center">

You can add attributes to an existing Element object by treating it as a dictionary, storing the new attribute value under a key consisting of the attribute name. For example, another way to do the example above:

majorHead = Element ( body, "blockquote" )
majorHead["align"] = "center"


You may want to supply attributes whose names are also Python keywords, such as "class=...". In that case, append an underbar (“_”) to the keyword name, and the Element constructor will remove the underbar when building the attribute.

For example, to construct an element that is a child of some element parent, that starts with tag “<p class="scream"> ”, the constructor call would look like this:

    para = Element ( parent, 'p', class_='scream' )

13.3.1. Element methods

.update ( d )

To add several attributes to an Element at once, call this method and pass it a dictionary d whose keys are the attribute names, with corresponding attribute values.