【发布时间】:2016-01-27 14:50:41
【问题描述】:
我正在尝试解析一个简单的 XML 块,该块被传递到函数的参数中。然后我想在最后一个 <cd> 元素中返回标题,在此:'Still got the blues'。出于某种原因,我在执行此操作时遇到了麻烦(第一次解析 XML)。这是我现在的功能,它基于我从 xml.etree.ElementTree 文档中阅读的内容:
def get_last_title(xmlstr):
xml = ET.fromstring(xmlstr)
return xml.findall('cd')[-1:].findall('title').text
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>
'''
【问题讨论】: