xml - 读取、修改和写入xml
问题描述
我正在尝试读取一个 xml 文件,更新一个值,然后写入结果。
有问题的xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config SYSTEM config.dtd">
<config>
<module name="this">
<param name="importLabel" value="naksnadksnkas" />
</module>
</config>
读取和操作值
tree = et.parse("path/file.xml")
root = tree.getroot()
for child in root:
for sub in child:
if sub.tag == "param":
if sub.attrib['name'] == "importLabel":
sub.attrib['value'] == "working"
tree.write(open('output.xml', 'wb'))
然而,这返回AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'write'
我可以成功写入tree
文件,但这不会捕获我编辑的更新记录。
解决方案
我没有收到错误消息。主要问题是您在这一行中使用==
而不是:=
sub.attrib['value'] == "working"
代码可以简化。如果你想要一个特定的元素,只需使用find()
:
from xml.etree import ElementTree as et
tree = et.parse("path/file.xml")
param = tree.find(".//param")
if param.attrib['name'] == "importLabel":
param.attrib['value'] = "working"
tree.write('output.xml')
推荐阅读
- r - R 正则表达式捕获组并引用捕获的模式
- python - 有没有比这更好的方法来混合 websocket recv 和发送调用?
- javascript - 弃用警告:不推荐使用当前的服务器发现和监控引擎
- r - r中矩阵格式数据的相关性
- move - 如何在 Libra 测试网中创建自定义代币?
- javascript - 使用javascript的页脚asp.net core 2.2标签中的数据表页脚摘要
- python - Luigi:提交 PySpark 任务时没有此类文件或目录错误
- javascript - 识别无序列表中单击的按钮:React
- r - 在 R 中使用 pandoc 将 .docx 转换为 .md 时如何保留标题和副标题?
- tcl - 如何更改 tcl 程序的文本框背景颜色?