使用minidom.toprettyxml时出现空行

30 投票
7 回答
20992 浏览
提问于 2025-04-17 13:24

我一直在用minidom.toprettyxml来美化我的XML文件。当我创建XML文件并使用这个方法时,一切都很好。但是如果我在修改了XML文件之后使用这个方法(比如我添加了一些新的节点),然后再把它写回XML文件,我就会看到出现空行。每次更新的时候,空行会越来越多……

我的代码:

file.write(prettify(xmlRoot))


def prettify(elem):
    rough_string = xml.tostring(elem, 'utf-8') //xml as ElementTree
    reparsed = mini.parseString(rough_string) //mini as minidom
    return reparsed.toprettyxml(indent=" ")

结果是:

<?xml version="1.0" ?>
<testsuite errors="0" failures="3" name="TestSet_2013-01-23 14_28_00.510935" skip="0"     tests="3" time="142.695" timestamp="2013-01-23 14:28:00.515460">




    <testcase classname="TC test" name="t1" status="Failed" time="27.013"/>




    <testcase classname="TC test" name="t2" status="Failed" time="78.325"/>


    <testcase classname="TC test" name="t3" status="Failed" time="37.357"/>
</testsuite>

有什么建议吗?

谢谢。

7 个回答

2

用这个来解决关于行的问题

toprettyxml(indent=' ', newl='\r', encoding="utf-8")

7

我找到了解决这个问题的简单方法,只需要修改你prettify()函数的最后一行,改成这样:

def prettify(elem):
rough_string = xml.tostring(elem, 'utf-8') //xml as ElementTree
reparsed = mini.parseString(rough_string) //mini as minidom
return reparsed.toprettyxml(indent=" ", newl='')
33

我在这里找到了一个解决方案:http://code.activestate.com/recipes/576750-pretty-print-xml/

然后我把它改成可以处理字符串,而不是文件。

from xml.dom.minidom import parseString

pretty_print = lambda data: '\n'.join([line for line in parseString(data).toprettyxml(indent=' '*2).split('\n') if line.strip()])

输出结果:

<?xml version="1.0" ?>
<testsuite errors="0" failures="3" name="TestSet_2013-01-23 14_28_00.510935" skip="0" tests="3" time="142.695" timestamp="2013-01-23 14:28:00.515460">
  <testcase classname="TC test" name="t1" status="Failed" time="27.013"/>
  <testcase classname="TC test" name="t2" status="Failed" time="78.325"/>
  <testcase classname="TC test" name="t3" status="Failed" time="37.357"/>
</testsuite>

这可能会帮助你更容易地把它融入到你的函数中:

def new_prettify():
    reparsed = parseString(CONTENT)
    print '\n'.join([line for line in reparsed.toprettyxml(indent=' '*2).split('\n') if line.strip()])

撰写回答