将xml转换为字典的正确方法

时间:2014-05-20 17:53:38

标签: python xml python-3.x elementtree

我不确定这是否是将此xml结果转换为字典的最佳方法,除此之外,有没有正确的方法转换为dict?

来自http请求结果的

xml:

<Values version="2.0">
  <value name="configuration">test</value>
  <array name="configurationList" type="value" depth="1">
    <value>test</value>
  </array>
  <value name="comment">Upload this for our robot.</value>
  <array name="propertiesTable" type="record" depth="1">
    <record javaclass="com.wm.util.Values">
      <value name="name">date_to_go</value>
      <value name="value">1990</value>
    </record>
    <record javaclass="com.wm.util.Values">
      <value name="name">role</value>
      <value name="value">Survivor</value>
    </record>
    <record javaclass="com.wm.util.Values">
      <value name="name">status</value>
      <value name="value">living</value>
    </record>
    <record javaclass="com.wm.util.Values">
      <value name="name">user</value>
      <value name="value">John&amp;nbsp;Connor</value>
    </record>
  </array>
  <null name="propertiesList"/>
</Values>

将xml转换为字典的代码(正常工作)

from xml.etree import ElementTree

tree = ElementTree.fromstring(xml)
mom = []
mim = []
configuration = tree.find('value[@name="configuration"]').text
comment = tree.find('value[@name="comment"]').text
prop = (configuration, comment)
mom.append(prop)

for records in tree.findall('./array/record'):
    me = []
    for child in records.iter('value'):
        me.append(child.text)
    mim.append(me)

for key, value in mim:
    mi_dict = dict()
    mi_dict[key] = value
    mom.append(mi_dict)

print(mom)

结果(按预期工作):

[('test', 'Upload this for our robot.'), {'date_to_go': '1990'}, {'role': 'Survivor'}, {'status': 'living'}, {'user': 'John&nbsp;Connor'}]

编辑:

很抱歉,如果我不清楚,但所描述的代码正在按预期工作。但我不确定这是否是正确的方式(python方式,pythonic或干净)。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我认为它太糟糕了。您可以进行一些小的更改,使其更加pythonic

from xml.etree import ElementTree

tree = ElementTree.fromstring(xml)
mom = []
mim = []
configuration = tree.find('value[@name="configuration"]').text
comment = tree.find('value[@name="comment"]').text
prop = (configuration, comment)
mom.append(prop)

for records in tree.findall('./array/record'):
    mim.append([child.text for child in records.iter('value')])

mom += [{k:v} for k, v in mim.iteritems()]

print(mom)