xml.parsers.expat loading xml into a dict and whitespace
Steven Bethard
steven.bethard at gmail.com
Wed May 23 02:05:54 EDT 2007
kaens wrote:
> Let's say I write a simple xml parser, for an xml file that just loads
> the content of each tag into a dict (the xml file doesn't have
> multiple hierarchies in it, it's flat other than the parent node)
[snip]
> <options>
> <one>hey</one>
> <two>bee</two>
> <three>eff</three>
> </options>
>
> it prints out:
> " :
>
> three : eff
> two : bee
> one : hey"
I don't have a good answer for your expat code, but if you're not
married to that, I strongly suggest you look into ElementTree[1]::
>>> xml = '''\
... <options>
... <one>hey</one>
... <two>bee</two>
... <three>eff</three>
... </options>
... '''
>>> import xml.etree.cElementTree as etree
>>> tree = etree.fromstring(xml)
>>> d = {}
>>> for child in tree:
... d[child.tag] = child.text
...
>>> d
{'three': 'eff', 'two': 'bee', 'one': 'hey'}
[1] ElementTree is in the 2.5 standard library, but if you're stuck with
an earlier python, just Google for it -- there are standalone versions
STeVe
More information about the Python-list
mailing list