Iz M
Iz M

Reputation: 403

Parsing XML with xml.etree.ElementTree

I'm trying to parse a simple XML block that's passed into the parameter of a function. I then want to return the title within the last <cd> element, in this: 'Still got the blues'. For some reason I'm having trouble doing this (first time parsing XML). This is my function right now, which is based on what I've read from the xml.etree.ElementTree documentation:

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

The XML is 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 your 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 the blues</title>
        <artist sex="male">Gary Moore</artist>
        <country>UK</country>
        <company>Virgin records</company>
        <price>10.20</price>
        <year>1990</year>
    </cd>
</catalog>
'''

Upvotes: 1

Views: 1533

Answers (1)

alecxe
alecxe

Reputation: 474191

You are trying to slice the list of elements found, instead get the last element by -1 index and then use findtext() method to find the inner title:

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

Demo:

>>> import xml.etree.cElementTree as ET
>>> 
>>> xml_doc ='''<?xml version="1.0" encoding="ISO-8859-1"?>
    Your XML here
... '''
>>> 
>>> xml = ET.fromstring(xml_doc)
>>> print(xml.findall('cd')[-1].findtext('title'))
Still got the blues

Upvotes: 1

Related Questions