如何使用Python的minidom替换xml中属性的值

2024-06-17 12:22:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下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()

Tags: namexmlyearcountryprintrankdirectiongermany
2条回答

西缅的台词确实管用。

或者,您可以这样做:

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

以下行实际上不会更改XML:

print firstchild.attributes["name"].value.replace("Liechtenstein", "Germany")

它只获取该值,用该字符串中的德国替换列支敦士登并打印该字符串。它不会修改XML文档中的值。

您应该直接分配一个新值:

firstchild.attributes["name"].value = "Germany"

相关问题 更多 >