2012-07-20 82 views
1

我已经决定有一种方法可以从XML字符串中一般创建字典。从XML字符串/文件在Python中创建元组

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_dict,其中key是标签的名称,而value是标签之间的值?

+1

你确定你永远不会收到类似数组的数据吗? ' a b c' – icktoofay 2012-07-20 03:45:12

+0

我们假设我不会。 – Rico 2012-07-20 03:59:03

回答

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?