【问题标题】:getchildren removed for python 3.9为 python 3.9 删除了 getchildren
【发布时间】:2021-04-06 23:36:49
【问题描述】:

我阅读了以下内容: “自 3.2 版起已弃用,将在 3.9 版中删除:使用 list(elem) 或迭代。” (https://docs.python.org/3.8/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren)

我的代码适用于 python 3.8 及以下版本:

tree = ET.parse("....xml")
root = tree.getroot()
getID= (root.getchildren()[0].attrib['ID'])

但是,当我尝试为 python 3.9 更新它时,我无法

tree = ET.parse("....xml")
root = tree.getroot()
getID= (root.list(elem)[0].attrib['ID'])

我收到以下错误 AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'list'

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    “使用list(elem) 或迭代”的字面意思是list(root),而不是root.list()。以下将起作用:

    getID = list(root)[0].attrib['ID']
    

    您可以将任何可迭代对象包装在列表中,弃用说明特别告诉您root 是可迭代对象。由于只为一个元素分配列表效率很低,因此您可以获取迭代器并从中提取第一个元素:

    getID = next(iter(root)).attrib['ID']
    

    这是一个更紧凑的符号

    for child in root:
        getID = child.attrib['ID']
        break
    

    主要区别在于没有孩子时会在哪里引发错误(直接由next 与当您尝试访问不存在的getID 变量时)。

    【讨论】:

      【解决方案2】:

      错误表明你应该这样写:

      getID = list(root)[0].attrib['ID']
      

      调用list 迭代root 元素并为其提供子元素,同时将其转换为可以索引的列表

      【讨论】:

        猜你喜欢
        • 2021-05-07
        • 1970-01-01
        • 2021-06-08
        • 2019-02-15
        • 2012-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-30
        相关资源
        最近更新 更多