Using elementtree: replacing nodes

Fredrik Lundh fredrik at
Tue May 2 09:27:58 CEST 2006

André wrote:

> I've started using elementtree and don't understand how to use it to
> manipulate and replace nodes.  I know how to do this using a simple,
> but inefficient parser I wrote, but I'd rather learn to use a better
> tool - especially as it is to be added to the standard library.

> Now, I would like to find all <pre> tags of the "text" class and

    for pre in elem.getiterator("pre"):


    for pre in elem.findall(".//pre"):

> 1. change the class value

    pre.set("class", "value")

> 2. append another node ( <textarea> )
> 3. surround the both nodes by a third one ( <form> )

or in other words,

2. replace the <pre> with a <form> element that contains some
new contents derived from the old element

    # 1) build the new form
    form = Element("form")
    e = SubElement(form, "pre")
    e.set("class", "text2")
    e.text = pre.text
    e = SubElement(form, "textarea", cols=80, name="code")
    e = SubElement(form, "input", type="submit")

    # 2) mutate the pre element
    pre.tag = "form"
    pre[:] = [form]

for harder cases, a common pattern is:

    for parent in elem.getiterator():
        for index, child in enumerate(parent.findall("pre")):
            # the code in here can manipulate parent[i] and child

another approach is to build a parent map; see the parent_map code


More information about the Python-list mailing list