python - 使用 xml.etree.ElementTree 解析 XML

标签 python xml parsing

我正在尝试解析传递到函数参数中的简单 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/

相关文章:

C - 将 argv 的值分配给变量

python - Pydev for Eclipse 在重命名包时不会更改所有引用

c++ - C 或 C++ 中是否有轻量级的多部分/表单数据解析器?

python - 为什么我不能比较 python 2.7 中的集合和不可变集合

JQuery、XML 和标签名称中的句点

python 在 xml 文件中编码'(引用)

xml - XSD,顺序无关紧要,必须考虑 xml 更改

json - 使用 Go 正确解析 JSON 数据时出错

Python 按相同顺序对 2 个不同的 Size 列表进行排序?

python - 配置解析器 : Choosing name and value delimiter