Is it possible to auto-generate python class objects based on the hierarchical content of an XML file?
Let me explain a bit what I mean. Let’s suppose I have an XML file that contains (for the sake of simplicity) the following:
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>blah blah...etc...</description>
<calories>650</calories>
</food>
</breakfast_menu>
I like the way XML presents data and attributes, but I would like to use Python so I’m asking if there is a set of utilities that read the file above and create something like:
class breakfast_menu():
food = food(self, name="Belgian Waffles", price="$5.95", description="blah blah...etc...", calories=650)
Is this something feasible? Can anyone suggest a way/tool to do that?
Thank you in advance for your consideration.
Parse it with some XML parser (ElementTree for example). Get content from each food tag into a Python dictionary.
Unpack the dictionary when giving it to the function like this:
If the dictionary contains something like
my_dictionary = {'name':'Belgian Waffles', 'price':'$5.95'}, callingfood(**my_dictionary)will be the same as callingfood(name = 'Belgian Waffles', price = '$5.95'). For more information, look at Understanding kwargs in Python.