Parsing XML data
Sometimes, we will get an XML response from the server, and we have to parse the XML to extract the data. We can use the xml.etree.ElementTree
module to parse the XML files.
Getting ready
We have to install the required module, xml
:
pip install xml
How to do it...
Here is how we can parse XML data with XML module:
- First import the required modules. As this script is in Python 3, make sure that you import the correct modules:
from urllib.request import urlopen
from xml.etree.ElementTree import parse
- Now get the XML file with the
urlopen
method in theurllib
module:
url = urlopen('http://feeds.feedburner.com/TechCrunch/Google')
- Now parse the XML file with the
parse
method in thexml.etree.ElementTree
module:
xmldoc = parse(url)
- Now iterate and print the details in XML:
for item in xmldoc.iterfind('channel/item'): title = item.findtext('title') desc = item.findtext('description') date = item.findtext('pubDate') link = item.findtext('link') print(title) ...