I have this XML API I am trying to get information out of for stats. Here's my code and sample 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)
When I run the code and there are MORE than 1 <call id="x">
stanzas, this works fine. If there is only 1 <call id="x">
, then I get this error below.
Traceback (most recent call last):
File "temp.py", line 17, in <module>
id = c["@id"]
TypeError: string indices must be integers
When I print the contents of xml
, I get this, so I know that xml["calls"]["call"]["@id"]
should be there:
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')]))]))])
Thoughts?