使用toprettyxml()时换行问题

18 投票
8 回答
19664 浏览
提问于 2025-04-15 15:36

我现在在用Python脚本里的xml.dom模块中的toprettyxml()函数,但在处理换行符时遇到了一些麻烦。

如果我不使用newl这个参数,或者使用toprettyxml(newl='\n'),它会显示出好几个换行,而不是只有一个。

举个例子:

f = open(filename, 'w')
f.write(dom1.toprettyxml(encoding='UTF-8'))
f.close()

显示为:

<params>


    <param name="Level" value="#LEVEL#"/>


    <param name="Code" value="281"/>


</params>

有没有人知道问题出在哪里,以及我该怎么用这个函数?顺便说一下,我用的是Python 2.6.1。

8 个回答

5

toprettyxml(newl='') 在我的Windows系统上可以正常使用。

20

我找到另一个很棒的解决方案:

f = open(filename, 'w')
dom_string = dom1.toprettyxml(encoding='UTF-8')
dom_string = os.linesep.join([s for s in dom_string.splitlines() if s.strip()])
f.write(dom_string)
f.close()

上面的解决方案主要是去掉了由toprettyxml()生成的多余换行符,这些换行符在字符串中是没用的。

这个方案的输入来源于 -> 有什么简单的方法可以去掉Python字符串中的空行吗?

14

toprettyxml()这个函数真是让人头疼。它的问题不只是因为Windows系统和换行符'\r\n'。无论你给newl参数传什么字符串,都会发现它多加了很多行。而且,它还会添加一些额外的空白,这可能会在机器读取XML时造成麻烦。

这里有一些解决办法可以参考:
http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace

撰写回答