xmltodict does not return a list for one element

前端 未结 3 634
轮回少年
轮回少年 2021-01-17 10:18

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

import xmltodict

mydict = xmltodict.parse(xmlstringResults)    
for carsIn         


        
3条回答
  •  旧巷少年郎
    2021-01-17 10:38

    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...
    

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

提交回复
热议问题