gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:53:04 24 4
gpt4 key购买 nike

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

最佳答案

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

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

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

关于python - 使用 Python 创建文件时保留初始 XML 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58919497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com