【问题标题】:python: how to save physically the xml file after changepython:更改后如何物理保存xml文件
【发布时间】:2015-10-23 05:30:29
【问题描述】:

我有这个代码:

国家.xml:

<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria"/>
<neighbor direction="W" name="Switzerland"/>

和:

from xml.dom import minidom
xmldoc = minidom.parse('country.xml')
print(xmldoc.toxml())
country = xmldoc.getElementsByTagName("country")
firstchild = country[0]
print(firstchild.attributes["name"].value)
firstchild.attributes["name"].value = "Germany"
print(xmldoc.toxml())

该文件已将国家名称更改为: “列支敦士登” 到 “德国”

我的问题是如何将更改保存回 country.xml 文件? 谢谢

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:

    您可以简单地打开文件并将xmldoc.toxml() 的输出写入其中。示例 -

    ...
    with open('country.xml','w') as f:
        f.write(xmldoc.toxml())
    

    【讨论】:

      猜你喜欢
      • 2014-06-09
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多