I’ve decided it’d be nice to have a way to generically create a dictionary from an XML string.
import xml.etree.ElementTree as ET
response = '<some><generic><xml></xml></generic></some>'
targetTree = ET.fromstring(response)
# Do something cool here
for key in my_cool_dict:
print '{0} = {1}'.format(key, my_cool_dict[key])
I’ve found nifty ways of iterating through your elements:
for elem in targetTree.findall('some'):
for child in elem.getchildren():
print i.text
These kinds of things require I know the XML tags. What if I don’t know what I’m receiving? How can I create my_cool_dict where the key is the name of the tag and the value is the value between the tags?
If it is flat (that is, the dictionary will not contain other dictionaries), then this should work:
For example, if
some_parent_elementrepresents this element:Then run your code:
You’ll get this: