Python:访问xml文件中的嵌套子元素

Python:访问xml文件中的嵌套子元素,python,xml,celementtree,Python,Xml,Celementtree,我有一个xml文件,其结构如下: A. 普拉洛南 苏伊夫 拉路中心酒店 洛杉矶酒店 瓦努瓦兹 埃特塞利杜酒店 小勃朗峰 和python代码来解析它: 将xml.etree.cElementTree作为ET导入 parse_file=open(“file.xml”、“r”) 树解析文件=ET.parse(解析文件) root\u parse\u file=tree\u parse\u file.getroot() 对于root_parse_文件中的子级:#指向root的所有子级的子级 如果ch

我有一个xml文件,其结构如下:


A.
普拉洛南
苏伊夫
拉路中心酒店
洛杉矶酒店
瓦努瓦兹
埃特塞利杜酒店
小勃朗峰
和python代码来解析它:

将xml.etree.cElementTree作为ET导入
parse_file=open(“file.xml”、“r”)
树解析文件=ET.parse(解析文件)
root\u parse\u file=tree\u parse\u file.getroot()
对于root_parse_文件中的子级:#指向root的所有子级的子级
如果child.attrib.keys()中的“ref”:
#一些代码。。。
对于child中的subChild:#指向所有子元素的subChild,这是代码的第59行
打印(subChild.attrib['ref'])
#一些代码。。。
当我想迭代这个元素时


要获取所有嵌套元素并解析它们的属性,我在这一行中遇到以下错误:
print(subChild.attrib['ref'])
错误:


我的问题是如何迭代根元素的所有嵌套子元素?

要迭代特定标记的属性,可以使用以下代码(包含id的标记placeName):

输出:

{http://www.w3.org/XML/1998/namespace}id = ene.0
n = 0
key = geonames 644285
ref = http://www.geonames.org/644285
{http://www.w3.org/XML/1998/namespace}id = ene.3
n = 2
subtype = compound
key = osm 2272301
ref = http://www.openstreetmap.org/way/2272301
{http://www.w3.org/XML/1998/namespace}id = ene.1
n = 1
key = osm 178528565
ref = http://www.openstreetmap.org/node/178528565
{http://www.w3.org/XML/1998/namespace}id = ene.2
n = 0
key = osm 3379120
ref = http://www.openstreetmap.org/way/3379120
此处的文档->

from lxml import etree

tree = etree.parse("file.xml")

for attributes in tree.xpath("//placeName[(@xml:id)]"):
    for name, value in attributes.items():
        print(f'{name} = {value}')
{http://www.w3.org/XML/1998/namespace}id = ene.0
n = 0
key = geonames 644285
ref = http://www.geonames.org/644285
{http://www.w3.org/XML/1998/namespace}id = ene.3
n = 2
subtype = compound
key = osm 2272301
ref = http://www.openstreetmap.org/way/2272301
{http://www.w3.org/XML/1998/namespace}id = ene.1
n = 1
key = osm 178528565
ref = http://www.openstreetmap.org/node/178528565
{http://www.w3.org/XML/1998/namespace}id = ene.2
n = 0
key = osm 3379120
ref = http://www.openstreetmap.org/way/3379120