具有lxml的Python漂亮XML打印机 [英] Python pretty XML printer with lxml

查看:150
本文介绍了具有lxml的Python漂亮XML打印机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用"ugly" XML读取现有文件并进行一些修改后,无法进行漂亮的打印.我已经尝试过etree.write(FILE_NAME, pretty_print=True).

After reading from an existing file with 'ugly' XML and doing some modifications, pretty printing doesn't work. I've tried etree.write(FILE_NAME, pretty_print=True).

我有以下XML:

<testsuites tests="14" failures="0" disabled="0" errors="0" time="0.306" name="AllTests">
    <testsuite name="AIR" tests="14" failures="0" disabled="0" errors="0" time="0.306">
....

我这样使用它:

tree = etree.parse('original.xml')
root = tree.getroot()

...    
# modifications
...

with open(FILE_NAME, "w") as f:
    tree.write(f, pretty_print=True)

推荐答案

对我来说,直到我在这里注意到这个小窍门,这个问题才得以解决:

For me, this issue was not solved until I noticed this little tidbit here:

http://lxml.de /FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output

简短版本:

使用以下命令读取文件:

Read in the file with this command:

>>> parser = etree.XMLParser(remove_blank_text=True)
>>> tree = etree.parse(filename, parser)

这将重置"已经存在的缩进,从而允许输出正确生成自己的缩进.然后照常执行pretty_print:

That will "reset" the already existing indentation, allowing the output to generate it's own indentation correctly. Then pretty_print as normal:

>>> tree.write(<output_file_name>, pretty_print=True)

这篇关于具有lxml的Python漂亮XML打印机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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