1

我决定最好有一种方法可以从XML字符串中创建字典。

import xml.etree.ElementTree as ET

response = '<some><generic><xml></xml></generic></some>'
targetTree = ET.fromstring(response)

# Do something cool here

for key in my_cool_dict:
    print '{0} = {1}'.format(key, my_cool_dict[key])

我找到了迭代元素的好方法:

for elem in targetTree.findall('some'):
    for child in elem.getchildren():
        print i.text

这类事情需要我知道XML标签。如果我不知道我收到了什么怎么办?如何创建标签名称和标签之间的值my_cool_dictkeyvalue

4

1 回答 1

2

如果它是平的(也就是说,字典不会包含其他字典),那么这应该可以工作:

my_cool_dict = {}
for element in some_parent_element:
    my_cool_dict[element.tag] = element.text

例如,如果 some_parent_element表示此元素:

<question>
    <title>How do I make a `dict` from XML in Python?</title>
    <tags>python xml</tags>
    <body>Lorem ipsum dolor sit amet.</body>
</question>

然后运行您的代码:

for key in my_cool_dict:
    print '{0} = {1}'.format(key, my_cool_dict[key])

你会得到这个:

body = Lorem ipsum dolor sit amet.
tags = python xml
title = How do I make a `dict` from XML in Python?
于 2012-07-20T04:07:15.600 回答