[Tutor] XML: changing value of elements and writing to a file

Johan Geldenhuys johan at accesstel.com.au
Thu Jul 16 14:07:22 CEST 2009


Thanks Stefan (decided to continue with a new thread name),

I basically wants to create a loop that creates a tree, appends it to the
previous tree and write it all to one file...If that makes sense.

At the moment my tree is something like this:
"""
<Signal name="abcde">
	<Description>WhatEver</Description>
</Signal>
"""

Now I want to read a dictionary from somewhere and put new values in the
name and description. I know how to do that. Now I want to create a loop
that creates a new tree:
"""
<Signal name="qazwsx">
	<Description>HowDee</Description>
</Signal>
"""

Now I want to append these to the data I want to write to a single xml file.

"""
<Signal name="abcde">
	<Description>WhatEver</Description>
</Signal>
<Signal name="qazwsx">
	<Description>HowDee</Description>
</Signal>
"""

I was thinking of creating a new root element and appending each as a
subelement and then writing the root element to the file...

I just need some pointers on how to do that. 

Thanks

Johan



-----Original Message-----
From: tutor-bounces+johan=accesstel.com.au at python.org
[mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Stefan
Behnel
Sent: Thursday, July 16, 2009 7:23 PM
To: tutor at python.org
Subject: Re: [Tutor] XML: changing value of elements

Hi,

a new question usually merits a new thread. Especially after a longer time,
replies to older threads tend to remain unread as people simply don't
scroll down far enough to notice them.

You were lucky. :)


Johan Geldenhuys wrote:
> I have another question about writing the xml tree to a file.
> 
> Now, I have parsed and changed my xml tree, but I want to create the same
> tree multiple times with different values and write it to one file.
> 
> 
> Let's use this code:
> 
> 	import xml.etree.ElementTree as ET
> 	doc = ET.parse('signal1.xml')
> 	signal_node = doc.getroot()[0]
> 	signal_node.set('name', 'Test_Name')
> 
> I have this in a function and it returns the signal_node everytime I call
> it, but with a different values. 
> 
> So, How do I take the returned xml and write that to one xml file?

I'm not sure what you mean here. Do you mean: "multiple XML trees into a
single file"? Or each in its own file?

BTW, you don't need to re-parse the tree if all you want is to modify it
and write it back out. You can either keep changing the tree and write it
out multiple times, or deep-copy it (or parts of it) and start over for
each step. Although I guess that parsing might be faster than deep-copying,
especially for ElementTree.

Stefan

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor

Checked by AVG - www.avg.com 
Version: 8.5.387 / Virus Database: 270.13.16/2240 - Release Date: 07/15/09
17:58:00



More information about the Tutor mailing list