如何使用python获取XML的所有子节点?

rad*_*adh 6 python xml python-3.x

这是我的 XML 文件

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>
Run Code Online (Sandbox Code Playgroud)

如何拉取 的所有子节点country

例如,我需要输出为 ['rank','year','gdp','neighbor']

voi*_*pro 7

使用 ElementTree lib 拉出子节点。这可能对你有帮助。

import xml.etree.ElementTree as ET
tree = ET.parse("file.xml")
root = tree.getroot()
for child in root:
  print({x.tag for x in root.findall(child.tag+"/*")})
Run Code Online (Sandbox Code Playgroud)