Tuesday, May 24, 2011

Re: Parsing an XML feed using ElementTree

I'd really reallly suggest you to use lxml library for xml parsing -- it has xpath in it.

On Tue, May 24, 2011 at 2:13 PM, Sithembewena Lloyd Dube <zebra05@gmail.com> wrote:
Hi Everyone,

I am trying to parse an XML feed and display the text of each child node without any success. My code in the python shell is as follows:

>>>import urllib
>>>from xml.etree import ElementTree as ET

>>>content = urllib.urlopen('http://xml.matchbook.com/xmlfeed/feed?sport-id=&vendor=TEST&sport-name=&short-name=Po')
>>>xml_content = ET.parse(content)

I then check the xml_content object as follows:

>>>xml_content
<xml.etree.ElementTree.ElementTree instance at 0x01DC14B8>

And now, to iterate through its child nodes and print out the text of each node:

>>>for node in xml_content.getiterator('contest'):
...        name = node.attrib.get('text')
...        print name
...
>>>

Nothing is printed, even though the document does have 'contest' tags with text in them. If I try to count the contest tags and increment an integer (to see that the document is traversed) I get the same result - the int remains at 0.

>>> i = 0
>>> for node in xml_content.getiterator('contest'):
...     i += 1
...
>>> i
0

What am I getting wrong? Any hints would be appreciated.

--
Regards,
Sithembewena Lloyd Dube

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment