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

Python批量提取EmotionReport格式XML字段导出为CSV报错问询

问题根因
  1. Element.findall() 返回的是匹配到的元素列表,列表对象没有text属性,查找单个唯一标签应该使用Element.find()方法。
  2. XML元素是层级嵌套结构,你直接在根节点的一级子节点下查找所有目标标签,没有匹配实际的XML结构,无法定位到目标元素。
  3. 代码存在变量名拼写错误:你定义的存储结果的列表是rows,但是追加数据时写的是row.append。
  4. 示例XML中Description标签内容末尾带换行,需要清理多余空白。
修复后完整代码
import xml.etree.ElementTree as ET
import glob
import pandas as pd

cols = ["Date", "Time", "FileName", "Description", "FileSize", "FilePath"]
rows = []
# 标准库glob即可满足需求,无需额外安装glob2
for filename in glob.glob(r'C:\xml\*.xml'):
    xmlData = ET.parse(filename)
    rootXML = xmlData.getroot()
    # 按层级定位节点
    date = rootXML.find("DateTime/Date").text
    time = rootXML.find("DateTime/Time").text
    file_node = rootXML.find("SourceInformation/File")
    file_path = file_node.find("FilePath").text
    file_name = file_node.find("FileName").text
    file_size = file_node.find("FileSize").text
    desc = file_node.find("FileAudioInformation/Description").text.strip()
    # 追加数据到结果列表
    rows.append({
        "Date": date,
        "Time": time,
        "FileName": file_name,
        "Description": desc,
        "FileSize": file_size,
        "FilePath": file_path
    })

df = pd.DataFrame(rows, columns=cols)
# 输出CSV,加utf-8-sig编码避免Windows下打开乱码
df.to_csv("EmotionData.csv", encoding="utf-8-sig", index=True)
补充说明

如果你的部分XML可能存在标签缺失的情况,可以在每个find()后加判空逻辑,避免AttributeError,示例判空写法:
date = rootXML.find("DateTime/Date").text if rootXML.find("DateTime/Date") is not None else ""

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:54:02