我有一个XML文件,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Recipe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
我需要阅读它,修改它,然后把它写回来。这是一段代码:
from xml.etree import ElementTree
with open('base.xml', 'rt') as f:
tree = ElementTree.parse(f)
recipe = tree.find('')
t = recipe.find('Targets_Params/Target_Table/Target_Name')
t.text = "new Value"
output_file = open('new.xml', 'w' )
output_file.write(ElementTree.tostring(recipe))
output_file.close()
我的问题是,当我把文件写出来时,我根本没有得到第一行,而第二行只是出现:
<Recipe>
如何在保留原始结构的同时读取文件,修改文件并将其写出来?