我试图按字母顺序返回所有英国艺术家-我还没有完全理解XML解析。我从调试和文档中收集到的信息是,当您使用findall()方法时,它返回一个无法进一步导航的列表,这是否正确?那么,在这种情况下<cd>
,如何遍历父节点的子元素来查找country =='UK'的所有元素?提前致谢!
def get_uk_artists(xmlstr):
xml = ET.fromstring(xmlstr)
artist_list = []
for each in xml.findall('cd'):
if each.findall('./cd/country').text == 'UK':
artist_list.append(each.findall('artist').text)
return artist_list.sort()
XML是:
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>
'''
您可以使用:
import xml.etree.ElementTree as ET
xml = ET.fromstring(xml_doc)
artists = []
for cd in xml.findall('cd'):
if cd.find('country').text == 'UK':
artists.append(cd.find('artist').text)
artists.sort()
print(artists)
输出
['Bonnie Tyler', 'Gary Moore']
这将遍历cd
文档中的每个文档。如果cd
有一个country
文本等于子元素'UK'
中,cd
艺术家的名字被附加到艺术家的名单。artists.sort()
然后就地对列表进行排序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句