Coddy
Coddy

Reputation: 891

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

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

Upvotes: 5

Views: 15103

Answers (2)

Minas Abovyan
Minas Abovyan

Reputation: 701

Simeon's line does work.

Alternatively, you could do this:

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

Upvotes: 3

Simeon Visser
Simeon Visser

Reputation: 122376

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"

Upvotes: 5

Related Questions