python 3.9 中删除了 getchildren

Que*_*Bee 5 python xml elementtree

我读到了以下内容:“自 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'])

Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)

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

Mad*_*ist 7

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

getID = list(root)[0].attrib['ID']
Run Code Online (Sandbox Code Playgroud)

您可以将任何可迭代对象包装在列表中,并且弃用注释明确告诉您root是可迭代对象。由于仅为一个元素分配列表的效率相当低,因此您可以获取迭代器并从中提取第一个元素:

getID = next(iter(root)).attrib['ID']
Run Code Online (Sandbox Code Playgroud)

这是一个更紧凑的表示法

for child in root:
    getID = child.attrib['ID']
    break
Run Code Online (Sandbox Code Playgroud)

主要区别在于,当没有子项时(next当您尝试访问不存在的getID变量时直接通过 vs ),错误将在哪里引发。


Ant*_*ile 5

错误表明你应该这样写:

getID = list(root)[0].attrib['ID']
Run Code Online (Sandbox Code Playgroud)

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