python - Parsing XML with xml.etree.ElementTree -


i'm trying parse simple xml block that's passed parameter of function. want return title within last <cd> element, in this: 'still got blues'. reason i'm having trouble doing (first time parsing xml). function right now, based on i've read xml.etree.elementtree documentation:

def get_last_title(xmlstr):   xml = et.fromstring(xmlstr)   return xml.findall('cd')[-1:].findall('title').text 

the xml here:

xml_doc ='''<?xml version="1.0" encoding="iso-8859-1"?> <catalog>     <cd>         <title>empire burlesque</title>         <artist sex="male">bob dylan</artist>         <country>usa</country>         <company>columbia</company>         <price>10.90</price>         <year>1985</year>     </cd>     <cd>         <title>hide heart</title>         <artist sex="female">bonnie tyler</artist>         <country>uk</country>         <company>cbs records</company>         <price>9.90</price>         <year>1988</year>     </cd>     <cd>         <title>greatest hits</title>         <artist sex="female">dolly parton</artist>         <country>usa</country>         <company>rca</company>         <price>9.90</price>         <year>1982</year>     </cd>     <cd>         <title>still got blues</title>         <artist sex="male">gary moore</artist>         <country>uk</country>         <company>virgin records</company>         <price>10.20</price>         <year>1990</year>     </cd> </catalog> ''' 

you trying slice list of elements found, instead get last element -1 index , use findtext() method find inner title:

xml.findall('cd')[-1].findtext('title') 

demo:

>>> import xml.etree.celementtree et >>>  >>> xml_doc ='''<?xml version="1.0" encoding="iso-8859-1"?>     xml here ... ''' >>>  >>> xml = et.fromstring(xml_doc) >>> print(xml.findall('cd')[-1].findtext('title')) still got blues 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -