简体   繁体   English

为 python 3.9 删除了 getchildren

[英]getchildren removed for python 3.9

I read the following: "Deprecated since version 3.2, will be removed in version 3.9: Use list(elem) or iteration."我读到以下内容:“自 3.2 版以来已弃用,将在 3.9 版中删除:使用 list(elem) 或迭代。” ( https://docs.python.org/3.8/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren ) https://docs.python.org/3.8/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren

My code works for python 3.8 and below:我的代码适用于 python 3.8 及以下版本:

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

However, when I try to update it for python 3.9, I am unable to但是,当我尝试为 python 3.9 更新它时,我无法

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

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

"Use list(elem) or iteration" means literally list(root) , not root.list() . “使用list(elem)或迭代”的字面意思是list(root) ,而不是root.list() The following will work:以下将起作用:

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

You can wrap any iterable in a list, and the deprecation note specifically tells you root is iterable.您可以将任何可迭代对象包装在列表中,弃用说明特别告诉您root是可迭代的。 Since it's rather inefficient to allocate a list for just one element, you can get the iterator and pull the first element from that:由于只为一个元素分配一个列表是相当低效的,因此您可以获取迭代器并从中提取第一个元素:

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

This is a more compact notation for这是一个更紧凑的符号

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

The major difference is where the error will get raised when there is no child (directly by next vs when you try to access the non-existent getID variable).主要区别在于当没有孩子时(直接由next vs 当您尝试访问不存在的getID变量时)将引发错误。

the error is indicating you should write this:错误表明您应该这样写:

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

invoking list iterates over the root element giving its children and at the same time converting it to a list which can be indexed调用list遍历root元素并为其提供子元素,同时将其转换为可以索引的列表

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

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