Python xmltodict索引

2024-10-01 15:49:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个xmlapi,我正试图从中获取统计信息。以下是我的代码和示例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>

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

有什么想法?你知道吗


Tags: 代码nameidxmlcalljohntotalordereddict

热门问题