python - 如何在 python xml.etree 模块中插入换行符

标签 python xml escaping newline

我想像这样打印出xml:

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

我有一段这样的代码:

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

但它打印出来是这样的:

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

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

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

如何在“这是第 1 行”之间插入换行符和“这是第 2 行。”

最佳答案

使用 '\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')

将产生

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

这相当于

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

关于python - 如何在 python xml.etree 模块中插入换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16145738/

相关文章:

python - 如何通过 python setuptools 执行脚本或函数?

python - 使用 Pip 和 Anaconda 安装包 (Windows)

java - 如何将图像添加到可绘制资源文件

javascript - 将字符串中的点从charcode转换为十六进制(javascript)

python - Seaborn regplot 使用 datetime64 作为 x 轴

python - Django-tables2:如何使用访问器引入外部列?

java - 在java中解析一个非xml文件

html - SVG 中的中心路径

javascript - 如何使用 JavaScript 正则表达式在单词边界之间找到用户提供的字符串?

.net - 在 XML 文件中保存转义字符 0x1b