使用 minidom.toprettyxml 时出现空行 [英] Empty lines while using minidom.toprettyxml

查看:16
本文介绍了使用 minidom.toprettyxml 时出现空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 minidom.toprettyxml 来美化我的 xml 文件.当我创建 XML 文件并使用此方法时,一切正常,但是如果我在修改 xml 文件后使用它(例如我添加了一个额外的节点),然后我将它写回 XML,我得到了空行,每次更新时,我得到的空行越来越多......

I've been using a minidom.toprettyxml for prettify my xml file. When I'm creating XML file and using this method, all works grate, but if I use it after I've modified the xml file (for examp I've added an additional nodes) and then I'm writing it back to XML, I'm getting empty lines, each time I'm updating it, I'm getting more and more empty lines...

我的代码:

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>

有什么建议吗?

谢谢.

推荐答案

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

I found a solution here: http://code.activestate.com/recipes/576750-pretty-print-xml/

然后我将其修改为采用字符串而不是文件.

Then I modified it to take a string instead of a file.

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>

这可能会帮助您更轻松地将其应用到您的函数中:

This may help you work it into your function a little be easier:

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

这篇关于使用 minidom.toprettyxml 时出现空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆