带有lxml的Python漂亮的XML打印机

pro*_*eek 19 python lxml pretty-print

在用"丑陋"的XML读取现有文件并进行一些修改后,漂亮的打印不起作用.我试过了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">
....
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

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

...    
# modifications
...

with open(FILE_NAME, "w") as f:
    tree.write(f, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)

小智 46

对我来说,直到我注意到这个小小的问题才解决这个问题:

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

精简版:

使用以下命令读入文件:

>>> parser = etree.XMLParser(remove_blank_text=True)
>>> tree = etree.parse(filename, parser)
Run Code Online (Sandbox Code Playgroud)

这将"重置"已经存在的缩进,允许输出正确生成它自己的缩进.那么pretty_print正常:

>>> tree.write(<output_file_name>, pretty_print=True)
Run Code Online (Sandbox Code Playgroud)


Phi*_*ham 9

那么,根据API文档,lxml etree模块中没有"写入"方法.关于将漂亮的xml字符串打印到文件中,您有几个选项.您可以像这样使用tostring方法:

f = open('doc.xml', 'w')
f.write(etree.tostring(root, pretty_print=True))
f.close()
Run Code Online (Sandbox Code Playgroud)

或者,如果你的输入源是不完美和/或你想要更多的旋钮和按钮,配置了让你可以使用Python包装的整洁LIB之一.

http://utidylib.berlios.de/

import tidy
f.write(tidy.parseString(your_xml_str, **{'output_xml':1, 'indent':1, 'input_xml':1}))
Run Code Online (Sandbox Code Playgroud)

http://countergram.com/open-source/pytidylib

from tidylib import tidy_document
document, errors = tidy_document(your_xml_str, options={'output_xml':1, 'indent':1, 'input_xml':1})
f.write(document)
Run Code Online (Sandbox Code Playgroud)


Bjö*_*ist 7

以下是针对 Python 3 的固定答案:

from lxml import etree
from sys import stdout
from io import BytesIO

parser = etree.XMLParser(remove_blank_text = True)
file_obj = BytesIO(text)
tree = etree.parse(file_obj, parser)
tree.write(stdout.buffer, pretty_print = True)
Run Code Online (Sandbox Code Playgroud)

其中text是字节序列形式的 xml 代码。


小智 6

fp = file('out.txt', 'w')
print(e.tree.tostring(...), file=fp)
fp.close()
Run Code Online (Sandbox Code Playgroud)

  • 什么是e.tree? (3认同)