Re: [lxml-dev] Next question (Was: Beginner question)
Andreas Tille schrieb:
On Tue, 16 Oct 2007, Frederik Elwert wrote:
elif lname(elem) == 'vaccination': print 'vaccination status response:',\ elem.find('status').get('response') elif lname(elem) == 'therapy': print 'therapy status response:',\ elem.find('status').get('response')
I think this should help.
It sounds promissing but does not help:
elif event == 'end' and lname(elem) == 'vaccination': print 'vaccination:', etree.tostring(elem, pretty_print=True) stat = elem.find('status') if stat != None: print 'vaccination status response:', elem.find('status').get('response') else: print 'status not found'
vaccination: <vaccination> <status response="n"/> </vaccination>
status not found
Did I missed something?
Probably a namespace issue, I forgot that. In a namespace aware application, you would use something like elem.find('{http://my-namespace/}status') Now since you want to avoid namespaces, it will get a bit more tricky. Maybe something like this helps: elif event == 'end' and lname(elem) == 'vaccination': print 'vaccination:', etree.tostring(elem, pretty_print=True) try: print 'vaccination status response:', elem.xpath('./*[local-name() = "status"]')[0].get('response') except IndexError: print 'status not found' Or you simply iter the children and test for lname(): elif event == 'end' and lname(elem) == 'vaccination': print 'vaccination:', etree.tostring(elem, pretty_print=True) for child in elem: if lname(child) == 'status': print 'vaccination status response:', child.get('response') I cc'd this to the list, what I forgot to do before, since there are the experts that might have better ideas. Frederik
While you can 'work around' the namespace awareness of lxml with a lot of code and hassle, it's much faster, much easier and much more readable to just use namespaces, especially if you store the namespaced tag names in global constants (possibly in a separate module). Stefan
On Tue, 16 Oct 2007, Frederik Elwert wrote:
elif event == 'end' and lname(elem) == 'vaccination': print 'vaccination:', etree.tostring(elem, pretty_print=True) try: print 'vaccination status response:', elem.xpath('./*[local-name() = "status"]')[0].get('response') except IndexError: print 'status not found'
This works perfectly.
Or you simply iter the children and test for lname():
elif event == 'end' and lname(elem) == 'vaccination': print 'vaccination:', etree.tostring(elem, pretty_print=True) for child in elem:
This was the clue I was originally seeking for: I did not imagined that it is so simple to iterate over elem itself.
if lname(child) == 'status': print 'vaccination status response:', child.get('response')
I cc'd this to the list, what I forgot to do before, since there are the experts that might have better ideas.
Sure - I always prefer list replies. Many thanks for your help Andreas. -- http://fam-tille.de
participants (3)
-
Andreas Tille
-
Frederik Elwert
-
Stefan Behnel