473,763 Members | 3,901 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using elementtree: replacing nodes

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é

May 2 '06 #1
2 7089
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.getiterato r("pre"):

or

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.clear()
pre.tag = "form"
pre[:] = [form]

for harder cases, a common pattern is:

for parent in elem.getiterato r():
for index, child in enumerate(paren t.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
at

http://effbot.org/zone/element.htm#the-element-type

</F>

May 2 '06 #2
Fredrik Lundh wrote:
André wrote:
I've started using elementtree and don't understand how to use it to
manipulate and replace nodes.

[snip]
It was mostly the following step which I couldn`t figure out...
# 2) mutate the pre element
pre.clear()
pre.tag = "form"
pre[:] = [form]
[snip]
another approach is to build a parent map; see the parent_map code
at

http://effbot.org/zone/element.htm#the-element-type


Thanks!
</F>


May 2 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3413
by: Nikhil Patel | last post by:
Hi all, Following in a portion of an xml document. I would like to replace "nso:Proposal" node with its child "w:p" node programmatically. How can I do this? Thanks. <ns0:Proposal> <ns0:Company> <w:p> <w:r>
6
1632
by: peterbe | last post by:
I have an XML string coming in from one system that I'd like to tidy up and return in a very particular format. I'm picky! If the input is <SOMETHING attr1="foo1" attr2='foo2' > Then the output must be <something attr1="foo1"
0
1457
by: theFLY | last post by:
Hello there, I have an XML file of structure that looks like this: <?xml version="1.0"?> <documents> <header id="1"> <title></title> <prodGroup></prodGroup> <version> <major></major> <minor></minor>
0
1643
by: theFLY | last post by:
This has posted in the ASP sub-forum, to no avail I re-post here. Hello there, I have an XML file of structure that looks like this: <?xml version="1.0"?> <documents> <header id="1"> <title></title>
8
5492
by: Craig | last post by:
Hi there, I'm only new to Python so please bear with me. I using ElementTree to generate an XML file that will reference a DTD and an XSL file. The header information I want at the start of the file is as follows: <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="test.xsl"?> <!DOCTYPE BobActivityLog SYSTEM "test.dtd">
3
2061
by: Jan Danielsson | last post by:
Hello all, This is probably a mind numbingly brain dead question.. But how do I generate the following: <p>Current date:<br/>2000-01-01</p> ..using ElementTree? The <pelement kind of needs two text blocks, as far as I can tell?
2
4277
by: Rick Muller | last post by:
I'm a computational chemist who frequently dabbles in Python. A collaborator sent me a huge XML file that at one point was evidently modified by a now defunct java application. A sample of this file looks something like: <group type="struct"> <name>Test</name> <param type="string"> <name>File Name</name> <cTag>fileName</cTag>
0
1574
by: Zvi | last post by:
Hi All, I got trouble parsing xml returned by web service. XML data contains characters above 128, so ET.fromstring throws an error. Error is thrown from python's xmllib.py file, where it detects char above 128. I am replacing utf-8 encoding string in returned xml with 'ISO-8859-1', and then I call .encode with ISO-8859-1 param. Still I get the parsing error, illegal character. What's interesting is that if I define a string const and...
0
858
by: Gabriel Genellina | last post by:
En Mon, 09 Jun 2008 15:32:00 -0300, Marcelo de Moraes Serpa <celoserpa@gmail.comescribió: I don't think it's a problem with ElementTree. Perhaps you are writing the same (global) configuration file from several threads at the same time? You may need some locking mechanism in that case. -- Gabriel Genellina
0
9563
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9386
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10145
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9998
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9938
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2793
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.