Editing XML as a dictionary in python?

前端 未结 8 1173
深忆病人
深忆病人 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:40

    Adding this line

    d.update(('@' + k, v) for k, v in el.attrib.iteritems())
    

    in the user247686's code you can have node attributes too.

    Found it in this post https://stackoverflow.com/a/7684581/1395962

    Example:

    import xml.etree.ElementTree as etree
    from urllib import urlopen
    
    xml_file = "http://your_xml_url"
    tree = etree.parse(urlopen(xml_file))
    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)
    
        d.update(('@' + k, v) for k, v in el.attrib.iteritems())
    
        return d
    

    Call as

    xml_to_dict(root)
    

提交回复
热议问题