Using elementtree: replacing nodes

André andre.roberge at gmail.com
Mon May 1 20:24:15 EDT 2006


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.

I'll use a simple, but representative example.  Suppose I have the
following text, where I inserted blank lines to isolate the part I want
to manipulate.
===================
<html>
<body>
<p>
This is some text.
</p>

<pre class="text">
a = 6*7
print a
</pre>

<p>
Done.
</p>
</body>
</html>
====================
Now, I would like to find all <pre> tags of the "text" class and
1. change the class value
2. append another node ( <textarea> )
3. surround the both nodes by a third one ( <form> )
==================
<html>
<body>
<p>
This is some text.
<p>

<form>
<pre class="text2">
a = 6*7
print a
</pre>
<textarea cols=80 name="code">
</textarea>
<input type="submit"></input>
</form>

<p>
Done.
</p>
</body>
</html>
===============

Any help would be appreciated. 
André




More information about the Python-list mailing list