我正在尝试解析传递到函数参数中的简单 XML block 。然后我想返回最后 <cd>
内的标题元素,在此:“仍然有忧郁”。由于某种原因,我在执行此操作时遇到了困难(第一次解析 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>
'''
最佳答案
您正在尝试对找到的元素列表进行切片,通过 -1
索引获取最后一个元素,然后使用 findtext()
查找内部标题的方法:
xml.findall('cd')[-1].findtext('title')
演示:
>>> 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
关于python - 使用 xml.etree.ElementTree 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35040533/