Python xmltodict指示错误

时间:2015-04-16 18:32:24

标签: python xmltodict

我有这个XML API我试图从统计信息中获取信息。这是我的代码和示例XML:

xml.xml

<calls total="1">
    <call id="cc04cd2a-31ff-422e-9f9c-94f41eaa219d">
        <name>John Doe</name>
        <coSpace>324f9508-beca-4829-89ee-927898c5796e</coSpace>
        <callCorrelator>45962153-c0ff-41ef-bf39-e75f54085b4e</callCorrelator>
    </call>
</calls>

temp.py

import xmltodict

totalNumCospaces = 0
totalNumCallers = 0

with open('/root/xml.xml','r') as f:
    xml = xmltodict.parse(f.read())

total = xml["calls"]["@total"]

totalNumCospaces = totalNumCospaces + int(total)
# If we have more than 0 calls active, find the coSpaces and count the callers
if (int(total) > 0):
    callList = xml["calls"]["call"]
    for c in callList:
        id = c["@id"]
        totalNumCallers = totalNumCallers + get_coSpaceCallers(server, id)

当我运行代码并且有超过1个<call id="x">节时,这样可以正常工作。如果只有<call id="x">,那么我会在下面看到此错误。

Traceback (most recent call last):
  File "temp.py", line 17, in <module>
    id = c["@id"]
TypeError: string indices must be integers

当我打印xml的内容时,我知道了,所以我知道xml["calls"]["call"]["@id"]应该在那里:

OrderedDict([(u'calls', OrderedDict([(u'@total', u'1'), (u'call', OrderedDict([(u'@id', u'cc04cd2a-31ff-422e-9f9c-94f41eaa219d'), (u'name', u'John Doe'), (u'coSpace', u'324f9508-beca-4829-89ee-927898c5796e'), (u'callCorrelator', u'45962153-c0ff-41ef-bf39-e75f54085b4e')]))]))])

思想?

0 个答案:

没有答案