user2111880 user2111880 - 3 months ago 9
Python Question

xmltodict does not return a list for one element

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


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?

Answer

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.