python - 如何使用 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"/>
.
.
解决方案
重新分配给root[7].attrib['revision']
, 不是root[7].attrib['revision'].text
, 即
root[7].attrib['revision'] = 'changed_text_1'
推荐阅读
- r - R ggplot2 多个箱线图统计
- c# - 删除特定 API 调用的授权规则
- linux - 尝试使用 'aocl install' 安装 de5a_net_i2 驱动程序但失败
- javascript - 从 Cordova 插件的服务调用 javascript 方法
- java - 如何处理来自用户的大量潜在选择
- java - 如何移动物体 y 方向并产生“引力”
- deep-learning - 卷积自动编码器错误 - 'RuntimeError: 输入类型 (torch.cuda.ByteTensor) 和权重类型 (torch.FloatTensor) 应该相同'
- php - Laravel Eager Loading,多个相同的hasOne关系
- javascript - Fast-csv 将所有内容写在一行中。需要多线输出
- c++ - Recvfrom 在本地工作,但在执行之间的随机端口上没有收到任何内容