REALLY simple xml reader

Diez B. Roggisch deets at nospam.web.de
Thu Jan 31 12:00:43 CET 2008


Ricardo Aráoz schrieb:
> 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

That's a problem in your XML not being XML. Has nothing to do with 
element-tree - as one sees from the error-message "ExpatError". If you 
show it to us, we might see why.

> 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"?


Yes.

Diez



More information about the Python-list mailing list