如何使用python脚本编辑xml属性值

时间:2019-05-13 07:44:21

标签: 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"/>
.
.

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:-1)

浏览项目并更改版本属性

import xml.etree.ElementTree as ET

tree = ET.parse('in.xml')
root = tree.getroot()
projects = root.findall('.//project')
for idx, project in enumerate(projects):
    project.attrib['revision'] = 'changed_text_{}'.format(idx + 1)

tree.write(open('in.xml', 'wb'))

in.xml

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

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