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>

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)

コードを実行し、複数<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