python:如何在更改后物理保存 xml 文件

python: how to save physically the xml file after change

我有这个代码:

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())

该文档已将国家名称从: "Liechtenstein" 到 "Germany"

我的问题是如何将更改保存回 country.xml 文件? 谢谢

您可以简单地打开文件并将 xmldoc.toxml() 的输出写入其中。例子-

...
with open('country.xml','w') as f:
    f.write(xmldoc.toxml())