python 3.9 删除了 getchildren

getchildren removed for python 3.9

我阅读了以下内容: “从 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'

错误表明你应该这样写:

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

调用 list 遍历 root 元素给它的子元素,同时将其转换为可以索引的列表

“使用 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 变量时)。