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

Python ElementTree解析XML返回空属性的原因是什么?

问题原因解析
  • 输出里的{}是空属性字典,本质是因为你遍历的<Name>、<NumElts>、<DBL>这些XML元素本身就没有设置任何属性(比如id="xxx"这类键值对形式的属性),它们只有内部的文本内容,所以child.attrib返回空字典。
  • 标签名前的{http://www.ni.com/LVData}是XML命名空间标识,因为根元素<LVData>定义了xmlns="http://www.ni.com/LVData",这个命名空间会被所有子元素继承,ElementTree会把命名空间与标签名拼接后显示出来。

如果想获取这些元素的文本内容,应该用child.text,可以修改代码如下:

import xml.etree.ElementTree as ET

essai = '''<?xml version='1.0' standalone='yes' ?>
<LVData xmlns="http://www.ni.com/LVData">
<Version>18.0.1f4</Version>
<Cluster>
<Name>Out</Name>
<NumElts>34</NumElts>
<DBL>
<Name>Amplitude_Signal</Name>
<Val>0.30000000000000</Val>
</DBL>
</Cluster>
</LVData>'''          

root = ET.fromstring(essai)
for child in root[1]:
    print(child.tag, child.text)

运行后会输出元素的文本内容:

{http://www.ni.com/LVData}Name Out
{http://www.ni.com/LVData}NumElts 34
{http://www.ni.com/LVData}DBL 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 10:25:07