2

我有这个 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>

临时文件

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">节时,这工作正常。如果只有 1 <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')]))]))])

想法?

4

0 回答 0