1

我想像这样打印出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'而不是'&#x000A;',输出是这样的:

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

如何newline在“这是第 1 行”之间插入一个。和“这是第 2 行。”

4

1 回答 1

3

使用 '\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>
于 2013-04-22T11:17:14.443 回答