Python getchildren() 不适用于有效的 XML 树

mez*_*hic 2 python xml elementtree

如果我在 XML 文件上运行以下 python(请参阅 Q 的底部):

import xml.etree.ElementTree as ET
tree = ET.parse('C:\\temp\\test2.xml')
print(tree.getchildren())
Run Code Online (Sandbox Code Playgroud)

我收到错误:

AttributeError: 'ElementTree' 对象没有属性 'getchildren'

我将 XML 上传到在线验证器,它说 XML 没问题。

Jim*_*son 5

树本身没有getchildren()方法。

print(tree.getroot().getchildren())
Run Code Online (Sandbox Code Playgroud)

请注意,getchildren()已弃用。查看文档


小智 5

getchildren()已弃用。

所以使用list(elem),在你的情况下使用list(tree.getroot())

  • 有关弃用的更多信息:https://bugs.python.org/issue29209。`getchildren` 已在 Python 2.7 和 3.2 中弃用,并在 Python 3.9 中删除。 (2认同)