Cod*_*ddy 5 python xml replace minidom
我有以下 xml:
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria"/>
<neighbor direction="W" name="Switzerland"/>
</country>
Run Code Online (Sandbox Code Playgroud)
我想将值“列支敦士登”替换为“德国”,因此结果应如下所示:
<country name="Germany">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria"/>
<neighbor direction="W" name="Switzerland"/>
</country>
Run Code Online (Sandbox Code Playgroud)
到目前为止我已经做到了这一点:
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()
Run Code Online (Sandbox Code Playgroud)
以下行实际上并未更改 XML:
print firstchild.attributes["name"].value.replace("Liechtenstein", "Germany")
Run Code Online (Sandbox Code Playgroud)
它仅获取该值,将该字符串中的列支敦士登替换为德国,然后打印该字符串。它不会修改 XML 文档中的值。
您应该直接分配一个新值:
firstchild.attributes["name"].value = "Germany"
Run Code Online (Sandbox Code Playgroud)