python - 使用 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))
解决方案
<!-- Outside Comment -->
是根元素的兄弟(myXML
在代码中由 表示)。它不包含在 的输出中tostring(myXML)
。
但是,如果您创建一个ElementTree
实例并将其写入文件,它就可以工作。将代码段中的最后两行替换为以下行:
etree.ElementTree(myXML).write("Output.xml", pretty_print=True)
推荐阅读
- ebpf - 使用 setrlimit 限制 bpf 资源
- html - 在从快速服务器发送 HTML 文档之前对其进行编辑
- javascript - Chart.js 在运行时更改点的颜色
- c# - 未找到 ItemTapped 事件处理程序的正确签名
- python - 通过多个维度索引到列表中的方法
- javascript - 为什么我得到一个数组,其名称是我在索引 0 处分配给道具的名称,而我想在索引 1 处传递的实际道具?
- visual-studio - 如何编写脚本将我的 .NET Core Web 应用程序发布到 Docker Hub?
- triggers - 如何在 GitLab CI 中触发管道
- django - Pandas/Django - 无法将保存为文件字段的 csv 转换为数据框
- c - C 指针地址差异