首页 > 解决方案 > 如何使用 python 脚本编辑 xml 属性值

问题描述

我有一个 xml 文件,其中有许多项目标签,我想在其中使用 python 脚本编辑修订属性值。

 <project remote="check" name="hardware/hwcomposer"
    path="hardware/check/hwcomposer"
    revision="14e7b7f9ba028b291c027812c95d64ec3a9da570"/>

 <project remote="check" name="hardware/weaver"
    path="hardware/check/weaver"
    revision="2c5c1719204699963e332cd92092665e99443220"/>

我收到的建议仅用于修改标签之间的数据,而不是标签的属性值,并且 xml 文件也有许多其他标签。

import xml.etree.ElementTree as ET
from xml.dom.minidom import parseString

tree = ET.parse('xml_file.xml')
root = tree.getroot()

print( root[7].attrib['path'])

if root[7].attrib['path'] == 'hardware/check/hwcomposer':
 root[7].attrib['revision'].text = 'changed_text_1'/* It is not working as root[7].attrib['revision'] returns a text and so not able to set the attribute value.

预期结果:

.
.
 <project remote="check" name="hardware/hwcomposer" path="hardware/check/hwcomposer" revision="changed_text_1"/>

 <project remote="check" name="hardware/weaver" path="hardware/check/weaver" revision="changed_text_2"/>
.
.

标签: pythonxml

解决方案


重新分配给root[7].attrib['revision'], 不是root[7].attrib['revision'].text, 即

root[7].attrib['revision'] = 'changed_text_1'

推荐阅读