Editing XML as a dictionary in python?

前端 未结 8 1177
深忆病人
深忆病人 2020-12-31 18:11

I\'m trying to generate customized xml files from a template xml file in python.

Conceptually, I want to read in the template xml, remove some elements, change some

8条回答
  •  悲&欢浪女
    2020-12-31 18:36

    This'll get you a dict minus attributes... dunno if this is useful to anyone. I was looking for an xml to dict solution myself when i came up with this.

    
    
    import xml.etree.ElementTree as etree
    
    tree = etree.parse('test.xml')
    root = tree.getroot()
    
    def xml_to_dict(el):
      d={}
      if el.text:
        d[el.tag] = el.text
      else:
        d[el.tag] = {}
      children = el.getchildren()
      if children:
        d[el.tag] = map(xml_to_dict, children)
      return d
    

    This: http://www.w3schools.com/XML/note.xml

    
     Tove
     Jani
     Reminder
     Don't forget me this weekend!
    
    

    Would equal this:

    
    {'note': [{'to': 'Tove'},
              {'from': 'Jani'},
              {'heading': 'Reminder'},
              {'body': "Don't forget me this weekend!"}]}
    

提交回复
热议问题