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

2024-10-01 15:42:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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>

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

Tags: 文件instance代码orghttpwwwcommentxml
1条回答
网友
1楼 · 发布于 2024-10-01 15:42:31

<! Outside Comment >是根元素的同级元素(在代码中由myXML表示)。它不包括在tostring(myXML)的输出中

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

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

相关问题 更多 >

    热门问题