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

标签 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>

我想用“德国”替换值“列支敦士登”,因此结果应如下所示:

<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/

相关文章:

停止和等待算法的 Python 实现

适合菜鸟的 Python 数据包嗅探器和套接字

python - 如何在Python上使用RSA私钥和SHA256解密

c# - 从逗号分隔的属性值创建新元素

r - 如何用R中大数据框中的另一个序列替换特定的数字序列(每行)?

c# - 子字符串替换的问题

python - 单链接聚类

java - 将 XML 文档转换为 DOM4J 文档以提取特定节点的值

c# - 如何在WPF中的TextBlock中显示解析后的xml?

excel - 替换或替换所有非字母数字字符