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

使用lxml库在指定位置插入元素属性时遇AttributeError问题求助

使用lxml在指定位置插入XML元素属性的解决方法

你尝试在attr3属性前插入attr2属性时遇到了错误:AttributeError: attribute 'attrib' of 'lxml.etree._Element' objects is not writable,这是因为lxml中_Element对象的attrib是只读映射,无法直接通过赋值字典的方式覆盖。

下面是可行的解决代码:

from lxml import etree

xml = '<root attr0="val0" attr1="val1" attr3="val3" attr4="val4" attr5="val5"/>'
root = etree.fromstring(xml)

# 将现有属性转为可修改的列表,找到插入位置
attrib_list = list(root.items())
insert_index = root.keys().index('attr3')
# 插入目标属性
attrib_list.insert(insert_index, ('attr2', 'val2'))

# 清空原有属性,按顺序重新添加所有属性
root.attrib.clear()
for key, val in attrib_list:
    root.attrib[key] = val

# 输出结果
print(etree.tostring(root, encoding='utf-8').decode('utf-8'))

运行后会输出符合预期的XML字符串:<root attr0="val0" attr1="val1" attr2="val2" attr3="val3" attr4="val4" attr5="val5"/>

核心思路是:先把只读的属性集合转为可编辑的列表,插入新属性后,清空原元素的属性,再按顺序逐个添加属性,以此保证属性的排列顺序符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 23:47:07