首页 > 解决方案 > 使用 Python 创建文件时保留初始 XML 注释

问题描述

我的 Python 代码拉到存储在 SQL Server 中的 XML 文件下方,并使用 Print(result) 语句代码显示存储在 SQL Server 中的相同 XML 文件。

SQL Server 中的 XML 文件:

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

蟒蛇代码:

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

标签: pythonxmllxml

解决方案


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

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

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

推荐阅读