Editing XML as a dictionary in python?

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

    XML has a rich infoset, and it takes some special tricks to represent that in a Python dictionary. Elements are ordered, attributes are distinguished from element bodies, etc.

    One project to handle round-trips between XML and Python dictionaries, with some configuration options to handle the tradeoffs in different ways is XML Support in Pickling Tools. Version 1.3 and newer is required. It isn't pure Python (and in fact is designed to make C++ / Python interaction easier), but it might be appropriate for various use cases.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题