How to replace a value of an attribute in xml using Python minidom
minidom, python, replace, xml
Solution
The following line does not actually change the XML:
print firstchild.attributes["name"].value.replace("Liechtenstein", "Germany")
It only gets the value, replaces Liechtenstein with Germany in that string and prints that string. It does not modify the value in the XML document.
You should assign a new value directly:
firstchild.attributes["name"].value = "Germany"
Problem
I have the following xml: ``` <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria"/> <neighbor direction="W" name="Switzerland"/> </country> ``` I want to replace the value "Liechtenstein" with "Germany", so the result should look like: ``` <country name="Germany"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria"/> <neighbor direction="W" name="Switzerland"/> </country> ``` So far I am up to this point: ``` from xml.dom import minidom xmldoc = minidom.parse('C:/Users/Torah/Desktop/country.xml') print xmldoc.toxml() country = xmldoc.getElementsByTagName("country") firstchild = country[0] print firstchild.attributes["name"].value #simple string mathod to replace print firstchild.attributes["name"].value.replace("Liechtenstein", "Germany") print xmldoc.toxml() ```