Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python xml.etree模块中插入换行符_Python_Xml_Escaping_Newline - Fatal编程技术网

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

如何在python xml.etree模块中插入换行符,python,xml,escaping,newline,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.' + '&

我想这样打印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>
<xml>
    <tag>this is line 1. this is line 2.</tag>
</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>
<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>
这是第1行。
这是2号线。
这相当于

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

这是一号线。
这是2号线。

为什么要尝试使用XML转义码而不是常规换行符?@MartijnPieters,因为
\n
根本不起作用。对我来说是这样的。你是如何验证它不起作用的?@MartijnPieters我已经用“\n”发布了我的输出。我知道,我看到了。但我无法复制这种输出,它不起作用。”这是第一行。'这是第二行。'仍然在同一行。你是什么意思?您是否无法生成我说过的上述代码将输出的输出?与您的不一样。这两行在我的输出中位于同一行。我在我的帖子中发布了我的输出。嗨,HennyH,您使用什么web浏览器来正确显示xml?