如何在python中插入换行符xml.etreemodu装置

2024-10-01 13:29:15 发布

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

我想打印出这样的xml:

<xml>
    <tag>
        this is line 1.
        this is line 2.
    </tag>
</xml>

我有一段代码是这样的:

^{pr2}$

但打印出来是这样的:

<xml>
    <tag>this is line 1.&#x000A;this is line 2.</tag>
</xml>

当我使用'\n'而不是'&#x000A;'时,输出如下:

<xml>
    <tag>this is line 1. this is line 2.</tag>
</xml>

如何在“this is line 1.”和“this is line 2”之间插入newline


Tags: 代码istaglinenewlinexmlthispr2
1条回答
网友
1楼 · 发布于 2024-10-01 13:29:15

使用'\n'生成新行,即

from xml.etree import ElementTree as ET
xml = ET.Element('xml')
tag = ET.SubElement(xml, 'tag')
tag.text = 'this is line 1.' + '\n' + 'this is line 2.'
tree = ET.ElementTree(xml)
tree.write('test.xml')

会产生

^{pr2}$

这相当于

<xml>
    <tag>
        this is line 1.
        this is line 2.
    </tag>
</xml>

相关问题 更多 >