【问题标题】:Parsing XML with xml.etree.ElementTree使用 xml.etree.ElementTree 解析 XML
【发布时间】: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>
'''

【问题讨论】:

    标签: python xml parsing


    【解决方案1】:

    您正在尝试对找到的元素列表进行切片,而不是通过-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
    

    【讨论】:

    • 谢谢@alecxe!像魅力一样工作。那么在这种情况下 element.findall('title').text 不起作用吗? element.find('title').text 呢?
    • @Izzy 是的,element.find('title').text 也可以。
    • 谢谢!你知道我如何通过诸如 sex="female" 之类的属性进行搜索吗?显然不是 element.findall('artist', sex="female").text :p
    • @Izzy 当然,xpath 支持有限,但应该足够了:element.findall('//artist[@sex="female"]'))
    • 谢谢!知道为什么会出现此错误吗?: SyntaxError: cannot use absolute path on element
    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多