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

如何用Python将XML转为字典列表?解决TypeError报错

解决XML转字典列表的循环报错问题

你的TypeError: element indices must be integers错误,是因为循环时错误地用元素对象而非整数作为索引访问节点导致的。结合你的XML结构( -> -> 多个),以下是两种可靠的实现方式:

方式一:层级遍历子节点

假设你的XML结构如下:

<root>
  <child>
    <record attr1="value1" attr2="value2" ... />
    <record attr1="value3" attr2="value4" ... />
  </child>
</root>

直接通过层级节点遍历所有:

import xml.etree.ElementTree as ET

# 解析XML文件(若为字符串则用ET.fromstring(xml_str))
tree = ET.parse("your_xml_file.xml")
root = tree.getroot()

# 获取<child>节点,遍历其下所有<record>
child_node = root[0]
records = []
for record in child_node:
    records.append(record.attrib)

方式二:用XPath精准定位(更健壮)

如果XML层级可能有变动,用XPath表达式直接定位所有节点更稳妥:

import xml.etree.ElementTree as ET

tree = ET.parse("your_xml_file.xml")
root = tree.getroot()

# 通过XPath匹配所有<child>下的<record>节点,生成字典列表
records = [record.attrib for record in root.findall("./child/record")]

错误原因说明

你用root[0][0].attrib能拿到第一条记录,是因为root[0]是节点,root[0][0]是用整数索引访问第一个;但循环时如果错误地尝试用遍历得到的元素对象作为索引(比如root[0][record]),就会触发类型错误——直接遍历节点本身即可,无需再用索引访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:05:16