使用 Python 创建文件时保留初始 XML 注释

Retain Initial XML Comments when file is created using Python

我的 Python 代码拉到存储在 SQL 服务器中的 XML 文件下方,并使用 Print(result) 语句代码显示存储在 [=30= 中的相同 XML 文件] 服务器.

XML SQL 服务器中的文件:

<!-- Outside Comment -->
<xbrl xmlns='http://www.xbrl.org/2003/instance'
      xmlns:xbrli='http://www.xbrl.org/2003/instance'
      xmlns:link='http://www.xbrl.org/2003/linkbase'
      xmlns:xlink='http://www.w3.org/1999/xlink'
      xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
      xmlns:iso4217='http://www.xbrl.org/2003/iso4217'
      xmlns:HelloWorld='http://xbrl.squarespace.com/HelloWorld'
      xsi:schemaLocation='
       '>
    <!-- Inside Comment -->
</xbrl>

但是,当我将 Print(Results) 的输出写入文件时,它会删除初始注释:<!-- Outside Comment --> 并创建保留 <!-- Inside Comment --> 的文件。我想知道如何保留 <!-- Outside Comment -->

XML 已创建文件:

<xbrl xmlns="http://www.xbrl.org/2003/instance" xmlns:xbrli="http://www.xbrl.org/2003/instance"
      xmlns:link="http://www.xbrl.org/2003/linkbase" xmlns:xlink="http://www.w3.org/1999/xlink"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:iso4217="http://www.xbrl.org/2003/iso4217"
      xmlns:HelloWorld="http://xbrl.squarespace.com/HelloWorld" xsi:schemaLocation="        ">
    <!-- Inside Comment -->
</xbrl>

Python代码:

from lxml import etree
print(r)
myXML = etree.XML(r)
XML_file = open("Output.xml", "wb")
XML_file.write(etree.tostring(myXML, pretty_print = True))

<!-- Outside Comment --> 是根元素的兄弟元素(在代码中用 myXML 表示)。它不包含在 tostring(myXML).

的输出中

但是如果您创建一个 ElementTree 实例并将其写入文件,它就可以工作。用这一行替换代码段中的最后两行:

etree.ElementTree(myXML).write("Output.xml", pretty_print=True)