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

Python XML解析:如何提取XML文件中preset标签的a属性值

解决方法

你当前代码中.attrib返回的是preset节点所有属性组成的字典,只需从该字典中提取a键对应的取值即可。
修改后的完整代码如下:

import xml.etree.ElementTree as ET
tree = ET.parse('basics.xml')
root = tree.getroot()

x = root.find(".//*[@lid='diagnosticEcgSpeed']/preset").attrib['a']
print(x)

运行后即可直接输出目标值 -1。

如果需要避免a属性不存在时抛出异常,也可以使用get方法取值:

x = root.find(".//*[@lid='diagnosticEcgSpeed']/preset").attrib.get('a')

当a属性不存在时,上述代码会返回None而非直接报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:24:03