【问题标题】:Modify XML declaration with python用python修改XML声明
【发布时间】:2014-10-19 08:48:02
【问题描述】:

我有一个 XML 文档,我需要使用 minidom 在 XML 声明中添加一些内容。声明如下所示:

<?xml version="1.0"?>

我需要它看起来像这样:

<?xml version="1.0" encoding="UTF-16" standalone="no"?>

我知道如何使用 minidom 更改或添加属性,这在此处不起作用。

最简单的方法是什么?作为参考,我正在运行 python 3.3.3。

【问题讨论】:

  • 你能告诉我们你的代码关于使用 minidom 改变或添加属性吗?它会引发什么样的错误?

标签: python python-3.x minidom


【解决方案1】:

我不确定这是否可以通过 minidom 完成。不过你可以试试lxml

from lxml import etree

tree = etree.parse("test.xml")
string = etree.tostring(tree.getroot(), pretty_print = True, xml_declaration = True, standalone = False, encoding = "UTF-16")
with open("test2.xml", "wb") as f:
    f.write(string)

或多或少取自here

【讨论】:

  • 很有趣,很直接。但是,我得到的 test2.xml 有 standalone='yes',对此有什么想法吗?
  • 它必须是 standalone = False 而不是 standalone = "no"。然后它对我有用。
猜你喜欢
  • 2020-12-23
  • 1970-01-01
  • 2011-01-27
  • 1970-01-01
  • 2021-12-16
  • 2022-06-23
  • 2017-11-05
  • 2021-06-30
  • 2017-08-06
相关资源
最近更新 更多