使用POST
请求,我收到了此回复
<?xml version="1.0" encoding="UTF-8"?>
<response version="1.1">
<accommodations>
<accommodation name="accom1">
<concepts>
<concept name="concept1-1">
<boards>
<board name="board1-1">
<description>description</description>
</board>
<board name="board1-2">
<description>description</description>
</board>
</boards>
</concept>
<concept name="concept2-1">
<boards>
<board name="board2-1">
<description>description</description>
</board>
<board name="board2-2">
<description>description</description>
</board>
</boards>
</concept>
</concepts>
</accommodation>
<accommodation name="accom2">
<concepts>
<concept name="concept3-1">
<boards>
<board name="board3-1">
<description>description</description>
</board>
<board name="board3-2">
<description>description</description>
</board>
</boards>
</concept>
<concept name="concept4-1">
<boards>
<board name="board4-1">
<description>description</description>
</board>
<board name="board4-2">
<description>description</description>
</board>
</boards>
</concept>
</concepts>
</accommodation>
</accommodations>
</response>
然后,使用此脚本,我将此数据转换为字典以访问
attributes and put it to the database.
def etree_to_dict(t):
d = {t.tag: {} if t.attrib else None}
children = list(t)
if children:
dd = defaultdict(list)
for dc in map(etree_to_dict, children):
for k, v in dc.iteritems():
dd[k].append(v)
d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
my_result = ET.fromstring(my_response.decode('ascii', 'ignore'))
d = globalvars.etree_to_dict(my_result)
当我访问accommodation
的属性时,一切都很好:
my_data=d['response']['accommodations']['accommodation']
for n in my_data.get('accommodation'):
p = XMLData(
name = n.get('@name')
)
但是当我尝试遍历concept
或boards
时,出现错误list indices must be integers, not str
,在for
循环之后,我得到了字符串,但没有字典
for n in my_data.get('accommodation'):
for k, v in n['concepts'].iteritems():
print v['@name']
我应该如何遍历字典以具有基于属性的访问权限?非常感谢。
答案 0 :(得分:0)
accommodations
,concepts
和boards
是列表,而不是dict
。因此,请尝试如下迭代它们:
for accommodation in d['response']['accommodations']:
for concept in accommodation['concepts']:
print concept['@name']
for board in accommodation['boards']:
print board['@name']