python - XML Parsing Child Elements using xml.etree.ElementTree -
i'm trying return uk artists in alphabetical order--i'm not understanding xml parsing. i've gathered debugging , documentation when use findall() method returns list cannot further navigated, correct? how iterate on subelements of parent node, in case <cd>
, find of elements country=='uk'? in advance!
def get_uk_artists(xmlstr): xml = et.fromstring(xmlstr) artist_list = [] each in xml.findall('cd'): if each.findall('./cd/country').text == 'uk': artist_list.append(each.findall('artist').text) return artist_list.sort()
the xml is:
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 use:
import xml.etree.elementtree et xml = et.fromstring(xml_doc) artists = [] cd in xml.findall('cd'): if cd.find('country').text == 'uk': artists.append(cd.find('artist').text) artists.sort() print(artists)
output
['bonnie tyler', 'gary moore']
this loops on each cd
in document. if cd
has country
child element text equal 'uk'
, cd
artist name gets appended list of artists. artists.sort()
sorts list in-place.
Comments
Post a Comment