如何解决为 python 3.9 删除了 getchildren
我阅读了以下内容: “自 3.2 版起已弃用,将在 3.9 版中删除:使用列表(元素)或迭代。” (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
变量时)会在何处引发错误。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。