xmltodict不返回一个元素的列表 [英] xmltodict does not return a list for one element

查看:70
本文介绍了xmltodict不返回一个元素的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果车库"中只有一辆汽车",则以下代码会产生错误:

The following Code produces an error, if there is only one "car" in "garage":

import xmltodict

mydict = xmltodict.parse(xmlstringResults)    
for carsInGarage in mydict['garage']['car']:
    # do something...

原因是 mydict ['garage'] ['car'] 仅是存在多个"car"元素的列表.所以我做了这样的事情:

The Reason is that mydict['garage']['car'] is only a list if there is more than one element of "car". So I did something like this:

import xmltodict

mydict = xmltodict.parse(xmlstringResults)
if isinstance(mydict['garage']['car'], list):
    for carsInGarage in mydict['garage']['car']:
        # do something for each car...
else:
    # do something for the car

以获得运行代码.但是对于更高级的操作,这不是解决方案.

to get the code to run. But for more advanced operations this is no solution.

即使只有一个元素,有人知道要使用的某种功能吗?

Does someone know some kind of function to use, even if there is only one element?

推荐答案

这当然不是一种优雅的方法,但这就是我为使代码运行而所做的工作(如果有人遇到相同的问题,可以通过google找到它)):

This is of course not an elegant way, but this is what i have done to get the code run (if someone hase the same probleme an found this via google):

import xmltodict

def guaranteed_list(x):
    if not x:
        return []
    elif isinstance(x, list):
        return x
    else:
        return [x]

mydict = xmltodict.parse(xmlstringResults)    
for carsInGarage in guaranteed_list(mydict['garage']['car']):
    # do something...

但是我想我将再次编写我的代码,并按照评论之一说直接使用XML".

but i thing i will write my code again and "use XML directly" as one of the comments said.

这篇关于xmltodict不返回一个元素的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆