繁体   English   中英

为 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'

“使用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 vs 当您尝试访问不存在的getID变量时)将引发错误。

错误表明您应该这样写:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM