使用python的minidom编写迭代XML项目的最快方法?

时间:2012-08-14 07:45:46

标签: python xml minidom

feature放入字典中的最短代码/最快方法是什么,使用python的minidom来实现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>

我现在对widget的属性只是功能感兴趣。

输出将是 feature["camera"] = true feature["etc"] = false

1 个答案:

答案 0 :(得分:1)

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

或简称:

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