我试图按字母顺序返回所有英国艺术家——我不完全理解 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() 然后就地对列表进行排序。
