I have this code :
country.xml :
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria"/>
<neighbor direction="W" name="Switzerland"/>
and :
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())
the document has changed the name of the country from: "Liechtenstein" TO "Germany"
My question is how to save the change back to the country.xml file ? thanks
You can simply open the file and write the output of xmldoc.toxml()
to it. Example -
...
with open('country.xml','w') as f:
f.write(xmldoc.toxml())