我有以下 xml:
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria"/>
<neighbor direction="W" name="Switzerland"/>
</country>
我想用“德国”替换值“列支敦士登”,因此结果应如下所示:
<country name="Germany">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria"/>
<neighbor direction="W" name="Switzerland"/>
</country>
到目前为止我是这样的:
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()
最佳答案
下面这行实际上并没有改变 XML:
print firstchild.attributes["name"].value.replace("Liechtenstein", "Germany")
它只获取值,在该字符串中用德国替换列支敦士登并打印该字符串。它不会修改 XML 文档中的值。
您应该直接分配一个新值:
firstchild.attributes["name"].value = "Germany"
关于python - 如何使用 Python minidom 替换 xml 中的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20459389/