我有这样的代码:
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文件?由于
您可以简单地打开文件并将xmldoc.toxml()
的输出写入其中。例子——
...
with open('country.xml','w') as f:
f.write(xmldoc.toxml())