0

featurepython的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>

我现在对小部件的属性不感兴趣,只是功能。

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

4

1 回答 1

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')])
于 2012-08-14T08:25:50.443 回答