gpt4 book ai didi

Python lxml创建xml文件时在特定节点之间添加换行符

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

我正在使用 lxml 编写 XML 文件。我能够将整个 XML 文件写入一行:

<FIXML><Batch Total="3"><Hdr SendTime="2016-09-27T13:32:19-05:00"/><RepeatingNode Price="0.99" RptID="1"><Date Dt="2016-09-20"/></RepeatingNode><RepeatingNode Price="2.49" RptID="2"><Date Dt="2016-09-20"/></RepeatingNode><RepeatingNode Price="0.25" RptID="3"><Date Dt="2016-09-20"/></RepeatingNode></Batch></FIXML>

我可以使用 Pretty_print 参数来 pretty-print 它:

<FIXML>
<Batch Total="3">
<Hdr SendTime="2016-09-27T13:32:19-05:00"/>
<RepeatingNode Price="0.99" RptID="1">
<Date Dt="2016-09-20"/>
</RepeatingNode>
<RepeatingNode Price="2.49" RptID="2">
<Date Dt="2016-09-20"/>
</RepeatingNode>
<RepeatingNode Price="0.25" RptID="3">
<Date Dt="2016-09-20"/>
</RepeatingNode>
</Batch>
</FIXML>

但是,我想写入我的文件并仅在每个 ReapeatingNode 之后添加换行符。我还想避免任何缩进。我理想的输出文件如下所示:

<FIXML>
<Batch Total="3">
<Hdr SendTime="2016-09-27T13:32:19-05:00"/>
<RepeatingNode Price="0.99" RptID="1"><Date Dt="2016-09-20"/></RepeatingNode>
<RepeatingNode Price="2.49" RptID="2"><Date Dt="2016-09-20"/></RepeatingNode>
<RepeatingNode Price="0.25" RptID="3"><Date Dt="2016-09-20"/></RepeatingNode>
</Batch>
</FIXML>

下面是我的代码的框架:

import lxml.etree as et
fixml_node = et.Element("FIXML")
batch_node = et.SubElement(fixml_node, "Batch")
et.SubElement(batch_node, "Hdr")

for row in data:
repeating_node = et.SubElement(batch_node, "RepeatingNode")
et.SubElement(repeating_node, "Date")

complete_new_file = et.ElementTree(fixml_node)

complete_new_file.write("output_file")

# or below when pretty-printing
complete_new_file.write("output_file", pretty_print=True)

对于如何实现我想要的输出有什么建议吗?

最佳答案

我的解决方案是忽略 Pretty_print 参数,并在适用的情况下添加带有换行符的文本或尾部。新代码如下:

import lxml.etree as et

fixml_node = et.Element("FIXML")
fixml_node.text = "\n"

batch_node = et.SubElement(fixml_node, "Batch")
batch_node.text = "\n"
batch_node.tail = "\n"

header_node = et.SubElement(batch_node, "Hdr")
header_node.tail = "\n"

for row in data:
repeating_node = et.SubElement(batch_node, "RepeatingNode")
repeating_node.tail = "\n"

et.SubElement(repeating_node, "Date")

complete_new_file = et.ElementTree(fixml_node)

complete_new_file.write("output_file")

这是自定义整个文件中换行符位置的简单方法。我会把这个问题留一两天,看看是否有人有更好的解决方案。

关于Python lxml创建xml文件时在特定节点之间添加换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732757/

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