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

Python ElementTree .set()迭代设置XML属性仅返回最后元素问题解决

Python ElementTree 批量设置标签属性异常问题解决

我是一名编程新手,首次在Stack Overflow发帖提问。
我在使用ElementTree的.set()方法时遇到异常:使用f-string可以正常为recipes标签设置recipe_id属性,但设置recipe_name属性时,所有recipes标签最终都只取到name_list数组的最后一个元素。我对这个差异非常困惑,因为recipe_id的赋值逻辑是正常运行的,不确定是语法问题还是我对元素迭代逻辑的理解有偏差。

预期XML输出

<recipes recipe_id="1" recipe_name="Apples">
<recipes recipe_id="2" recipe_name="Oranges">

实际得到的输出

<recipes recipe_id="1" recipe_name="Oranges">
<recipes recipe_id="2" recipe_name="Oranges">

原问题代码

#!/usr/bin/env python3

import os
import os.path 
import xml.etree.ElementTree as ET

filename = "my_recipes.xml"
xmlTree = ET.parse(filename)
root = xmlTree.getroot()

#修改recipes的recipe id属性
i = 0 
for element in root.iter("recipes"):
    i += 1
    element.set('recipe_id', f"{i}")
 
 #遍历树中所有tbody节点
name_list = []
for tbody in root.iter("tbody"):
    #遍历所有row节点
    for row in tbody.findall('row'):
        data = row.find('entry').text
        #获取row对应属性
        rec_name = row.find('entry').attrib
        #筛选出包含食谱名称的row,暂未找到更精准的取值方法
        if rec_name == {'namest': 'c1', 'nameend': 'c2', 'align': 'left', 'valign': 'bottom'}:
            #提取名称存入name_list
            name_list.append(data)
 
for recipes in root.findall('recipes'):
    for i in range(len(name_list)):
        recipes.set('recipe_name', F"{name_list[i]}")
 
xmlTree.write(filename, encoding='UTF-8', xml_declaration=True)

对应XML结构

<?xml version='1.0' encoding='UTF-8'?>
<Root>
    <recipes>
        <tbody>
            <row>
                <entry namest="c1" nameend="c2" align="left" valign="bottom">Apples</entry>
            </row>
        </tbody>
    </recipes>
    <recipes>
        <tbody>
            <row>
                <entry namest="c1" nameend="c2" align="left" valign="bottom">Oranges</entry>
            </row>
        </tbody>
    </recipes>
</Root>

问题原因

原代码错误使用了嵌套循环:外层遍历每个recipes节点时,内层又完整遍历了整个name_list,相当于每个recipes节点都被依次赋值了name_list里的所有值,最终自然只会保留列表最后一个元素的取值。

正确解决方案

使用enumerate同时获取遍历的索引和对应的recipes节点,直接按索引匹配name_list里对应的名称赋值,保证节点和名称一一对应:

for i,recipes in enumerate(root.findall('recipes')):
    recipes.set('recipe_name',name_list[i])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:36:01