【问题标题】:How to replace a value of an attribute in xml using Python minidom如何使用 Python minidom 替换 xml 中的属性值
【发布时间】:2013-12-25 21:34:52
【问题描述】:

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

【问题讨论】:

  • 到目前为止你有什么?
  • 我可以访问该值,但不知道如何替换它。
  • 最好包含您拥有的代码,以便可以对其进行更新/修改以替换该值。

标签: python xml replace minidom


【解决方案1】:

以下行实际上并未更改 XML:

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

它只获取值,在该字符串中将 Liechtenstein 替换为 Germany 并打印该字符串。它不会修改 XML 文档中的值。

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

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

【讨论】:

    【解决方案2】:

    Simeon 的线路确实有效。

    或者,您可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      相关资源
      最近更新 更多