abhijeet thatte, 16.06.2010 20:41:
On Wed, Jun 16, 2010 at 10:57 AM, Stefan Behnel wrote:
You should start by writing down the XML structure that you want to build
for the above dict. That will make it clear what needs to be done.
/*****************************************************************************************/
I need an xml file structure as below:
<chipsim>
<#>
<name>sh2a</name>
<size>32</size>
<bus_width>4</bus_width>
<#><PIF>
<name>PIF</name>
<offset>4</offset>
<name_of_peer_string>new_string</name_of_peer_string>
</PIF>
<#><interrupt_tree>
<name>Interrupt_tree</name>
<#><tree_level_0>
<name>MX</name>
<offset>32</offset>
<bit_position>1</bit_position>
<type>INTR</type>
<hi_mask_def>0000</hi_mask_def>
<lo_mask_def>0000</lo_mask_def>
<#><tree_level_1>
<name>RRPR</name>
<offset>928</offset>
<bit_position>0</bit_position>
<type>INTR</type>
<hi_mask_def>0000</hi_mask_def>
<lo_mask_def>0000</lo_mask_def>
</tree_level_1>
</tree_level_0>
</interrupt_tree>
</chipsim>
//**************************************************************************************/
This is a very small part of the actual output I need.
Dicts which I am creating looks like =
{'chipsim':{'name':sh2a,'size':32,'bus_width':'4','PIF':{'name':'PIF','offseet':'4','name_of_peer_string':'new_string'},'interrupt_tree':{'tree_level_0':{'tree_level_1':{.....}}}}}
Now, that really makes it clear what you want. You can try this:
import xml.etree.ElementTree as ET
def to_xml_elements(d):
elements = []
# run through all items in the dict
for name, value in d.items():
element = ET.Element(name)
if isinstance(value, dict):
# this is a sub-dict => inject its content recursively
element[:] = to_xml_elements(value)
else:
# normal value => insert as string value
value_element = ET.Element(key)
value_element.text = str(value)
element.append(value_element)
# return list of elements that were created from the dict
return elements
I guess ElementTree is the best way to go about it. But have not found a
good reference on how to use it.
There's lots of info on the web. Start at the effbot site:
http://effbot.org/zone/element-index.htm
Stefan
--
http://mail.python.org/mailman/listinfo/python-list