Search code examples
pythonxmlminidom

Fastest way to code iteration through XML items using python's minidom?


What would be the shortest code/fastest way to put the feature in a dictionary, using python's minidom for this structure of xml:

<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns       = "http://www.w3.org/ns/widgets"
        id          = "http://example.org/exampleWidget"
        version     = "2.0 Beta"
        height      = "200"
        width       = "200"
        viewmodes   = "fullscreen">

<feature name="http://example.com/camera" state="true"/>
<feature name="http://example.com/bluetooth" state="true"/>
<feature name="http://example.com/sms" state="true"/>
<feature name="http://example.com/etc" state="false"/>
</widget>

I'm not interested for now in widget's attributes just the features.

The output would be feature["camera"] = true feature["etc"] = false


Solution

  • from xml.dom.minidom import parseString
    from os.path import basename
    
    dom = parseString(raw_xml)
    
    feature = {}
    for f in dom.getElementsByTagName('feature'):
        name = basename(f.getAttribute('name'))
        state = f.getAttribute('state').lower() == 'true'
        feature[name] = state
    

    Or in SHORT:

    dict([(basename(f.getAttribute('name')), f.getAttribute('state').lower() == 'true')
      for f in parseString(raw).getElementsByTagName('feature')])