使用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>
</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>
</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>
以下是请求代码:
my_request = urllib2.Request(url, message)
response_xml = urllib2.urlopen(my_request)
my_response = response_xml.read()
然后我将字符串转换为字典:
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)
然后我尝试将一些数据从字典保存到数据库。当我尝试保存name="accom1"
时,everythig可以正常工作:
my_data=d['response']['accommodations']['accommodation']
for n in my_data.get('accommodation'):
p = XMLData(
name = n.get('@name')
)
但是当我尝试保存board
name
时,出现了一个错误:
list indices must be integers, not str
my_data=d['response']['accommodations']['accommodation']['concepts']
for n in my_data:
p = XMLData(
board = n['@name']
)
我不知道为什么会这样。你能帮我吗?非常感谢。