0

I'm using xmltodict in Python 3.7.6 and am running into an issue where sometimes my data is a list and sometimes my data is an Ordered Dictionary. Here's a code exert:

import xmltodict
myData = list()

myData.append (xmltodict.parse("""
<DataTimes>
<DataTime>
<FromTime>00:00:00</FromTime>
<ToTime>23:59:59</ToTime>
</DataTime>
</DataTimes> """))
myData.append (xmltodict.parse("""
<DataTimes>
<DataTime>
<FromTime>00:00:00</FromTime>
<ToTime>01:00:00</ToTime>
</DataTime>
<DataTime>
<FromTime>03:00:00</FromTime>
<ToTime>04:00:00</ToTime>
</DataTime>
<DataTime>
<FromTime>06:00:00</FromTime>
<ToTime>07:00:00</ToTime>
</DataTime>
</DataTimes>""") )

for i in range(len(myData)):
    for values in myData[i].get("DataTimes").values():
        print(type(values))
        if isinstance(values, list): #treat the data as a list
           for myDataTime in values:
              print(myDataTime.get("FromTime"))
        else: #treat the data as a dictionary
             print(values.get("FromTime"))

I have to continuously write a list check for every new data input I'm looking at in my data as I can never be sure if I'll have one set of data in index[0] or multiple sets of data in index[1]. Is there a cleaner way to get access to either a list or an ordered dictionary?

SydV
  • 3
  • 3
  • Looks to me like this is a consequence of `xmltodict` trying to pretend XML is something it's not. `xmltodict` is designed to make XML feel like JSON, but XML has a fundamentally very different design from JSON. – user2357112 Jun 12 '20 at 04:52
  • With a parser that reflects the structure of XML better, like lxml, this kind of problem doesn't happen. – user2357112 Jun 12 '20 at 04:54

0 Answers0