[Tutor] XML: changing value of elements and writing to a file
Stefan Behnel
stefan_ml at behnel.de
Thu Jul 16 17:07:00 CEST 2009
Johan Geldenhuys wrote:
> Thanks Stefan (decided to continue with a new thread name),
... which isn't quite enough. As long as you reply to the mail, e-mail/news
readers will still sort it into the original thread, so many people will
not see it.
> 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...
That's exactly the right thing since XML requires a single root element.
You can do it like this:
root = ET.Element("newroot")
for key, value in some_dict.iteritems():
signal = ET.SubElement(root, "Signal", name=key)
ET.SubElement(signal, "Description").text = value
Reading this might help:
http://effbot.org/zone/element.htm
http://codespeak.net/lxml/tutorial.html#the-element-class
Stefan
More information about the Tutor
mailing list