我有这段代码:
country.xml:
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria"/>
<neighbor direction="W" name="Switzerland"/>
和:
from xml.dom import minidom
xmldoc = minidom.parse('country.xml')
print(xmldoc.toxml())
country = xmldoc.getElementsByTagName("country")
firstchild = country[0]
print(firstchild.attributes["name"].value)
firstchild.attributes["name"].value = "Germany"
print(xmldoc.toxml())
该文件更改了该国家/地区的名称: “列支敦士登” 至 “德国”
我的问题是如何将更改保存回country.xml文件? 感谢
答案 0 :(得分:3)
您只需打开文件并将xmldoc.toxml()
的输出写入其中即可。示例 -
...
with open('country.xml','w') as f:
f.write(xmldoc.toxml())