How to replace a value of an attribute in xml using Python minidom

Coddy picture Coddy · Dec 8, 2013 · Viewed 13.2k times · Source

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

Answer

Minas Abovyan picture Minas Abovyan · Jan 19, 2014

Simeon's line does work.

Alternatively, you could do this:

firstchild.setAttribute('name', 'Germany')