Python and XML class objects

Is it possible to auto-generate python class objects based on the hierarchical content of an XML file?
Let me explain a little what I mean. Suppose I have an XML file containing (for 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 represents data and attributes, but I would like to use Python, so I ask if there are a set of utilities that read the above file and create something like:

 class breakfast_menu(): food = food(self, name="Belgian Waffles", price="$5.95", description="blah blah...etc...", calories=650) 

Is it possible? Can anyone suggest a way / tool for this? Thank you in advance for your consideration.

+4
source share
2 answers

Split it into some XML parser (e.g. ElementTree). Get content from each food tag into a Python dictionary. Unzip the dictionary by providing it with this function:

 food(**my_dictionary) 

If the dictionary contains something like my_dictionary = {'name':'Belgian Waffles', 'price':'$5.95'} , calling food(**my_dictionary) will be the same as calling food(name = 'Belgian Waffles', price = '$5.95') . For more information, see Understanding kwargs in Python .

+5
source

It sounds like you need something like the ElementTree XML API: http://docs.python.org/library/xml.etree.elementtree.html

-1
source

Source: https://habr.com/ru/post/1439848/


All Articles