REALLY simple xml reader

Ricardo Aráoz ricaraoz at gmail.com
Thu Jan 31 06:38:51 EST 2008


Ivan Illarionov wrote:
>>>> from xml.etree import ElementTree as et
>>>> from decimal import Decimal
>>>>
>>>> root = et.parse('file/with/your.xml')
>>>> debits = dict((debit.attrib['category'], Decimal(debit.find('amount').text)) for debit in root.findall('debit'))
>>>>
>>>> for cat, amount in debits.items():
> ...   print '%s: %s' % (cat, amount)
> ...
> food: 24.30
> car: 909.56
> medical: 188.20
> savings: 25
> withdrawal: 40
> supplies: 10.58
> clothes: 31.19
> 

Thanks Ivan, it seems a elegant API, and easy to use.
I tried to play a little with it but unfortunately could not get it off
the ground. I kept getting
>>> root = et.fromstring(doc)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "E:\Python25\lib\xml\etree\ElementTree.py", line 963, in XML
    parser.feed(text)
  File "E:\Python25\lib\xml\etree\ElementTree.py", line 1245, in feed
    self._parser.Parse(data, 0)
ExpatError: XML or text declaration not at start of entity: line 2, column 0

But it's probably my lack of knowledge on the subject. Well, I guess
there is no free ride and I'll take a look at ElementTree as soon as I
have some spare time, looks promising.
One last question. Am I right to believe "debit" would be an "et" object
of the same class as "root"?
THX



More information about the Python-list mailing list