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

7.8. The SubElement() constructor

This is a handy constructor that accomplishes the two basic operations in adding an element to a tree:

Here is the general form:

SubElement(parent, tag, attrib={}, nsmap=None, **extras):

The first argument, parent, is the Element instance under which the newly created Element instance is to be added as its next child. The tag, attrib, nsmap, and **extras arguments work exactly the same as they do in the call to Element() described in Section 7.2, “The Element() constructor”.

The return value is the newly constructed Element.

Here's an example. Suppose you want to build this XML:

<state name="New Mexico">
  <county name="Socorro">
    <ppl name="Luis Lopez"/>
  </county>
</state>

Here's the code to build it, and then display it, interactively:

>>> st=etree.Element('state', name='New Mexico')
>>> co=etree.SubElement(st, 'county', name='Socorro')
>>> ppl=etree.SubElement(co, 'ppl', name='Luis Lopez')
>>> print etree.tostring(st)
<state name="New Mexico"><county name="Socorro"><ppl name="Luis Lopez"/>
</county></state>
>>>