You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用xml.etree.ElementTree获取XML中的自闭合标签名称

解决方法

你的问题出在试图通过text属性获取标签名,但<annual/>是<Type>的子元素,并非文本内容。要获取它的标签名,需要先定位到<Type>节点,再获取其下子元素的tag属性。另外你原代码里node.find("Type>")多了个右尖括号,这也是定位失败的原因之一。

正确代码示例

import xml.etree.ElementTree as et

xtree = et.parse(xml)
xroot = xtree.getroot()

# 定位到Type节点
type_node = xroot.find("Type")
# 遍历Type节点下的子元素,获取标签名
for child in type_node:
    print(child.tag)  # 输出: annual

如果确定<Type>下只有这一个子元素,也可以直接通过索引快速获取:

type_node = xroot.find("Type")
annual_tag = type_node[0].tag
print(annual_tag)

关键说明

tag是ElementTree元素对象的内置属性,专门用于存储元素的标签名称,正好对应你要获取的annual。

内容的提问来源于stack exchange,提问作者Xiaowan Wen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 10:45:42