用Python打印XML的最佳方法(或各种方法)是什么?
当前回答
从Python 3.9开始,ElementTree有一个用于漂亮打印XML树的indent()函数。
见https://docs.python.org/3/library/xml.etree.elementtree.html # xml.etree.ElementTree.indent。
示例用法:
import xml.etree.ElementTree as ET
element = ET.XML("<html><body>text</body></html>")
ET.indent(element)
print(ET.tostring(element, encoding='unicode'))
好处是它不需要任何额外的库。欲了解更多信息,请访问https://bugs.python.org/issue14465和https://github.com/python/cpython/pull/15200
其他回答
我遇到了这个问题,我是这样解决的:
def write_xml_file (self, file, xml_root_element, xml_declaration=False, pretty_print=False, encoding='unicode', indent='\t'):
pretty_printed_xml = etree.tostring(xml_root_element, xml_declaration=xml_declaration, pretty_print=pretty_print, encoding=encoding)
if pretty_print: pretty_printed_xml = pretty_printed_xml.replace(' ', indent)
file.write(pretty_printed_xml)
在我的代码中,这个方法是这样调用的:
try:
with open(file_path, 'w') as file:
file.write('<?xml version="1.0" encoding="utf-8" ?>')
# create some xml content using etree ...
xml_parser = XMLParser()
xml_parser.write_xml_file(file, xml_root, xml_declaration=False, pretty_print=True, encoding='unicode', indent='\t')
except IOError:
print("Error while writing in log file!")
这只是因为etree默认使用两个空格来缩进,我发现这不是很强调缩进,因此不漂亮。我找不到任何树的设置或任何函数的参数来改变标准树缩进。我喜欢使用etree的简单性,但这真的让我很恼火。
XML pretty print for python看起来很适合这个任务。(名字也很恰当。)
另一种方法是使用pyXML,它有一个PrettyPrint函数。
另一个解决方案是借用这个缩进函数,用于自2.5以来内置在Python中的ElementTree库。 下面是它的样子:
from xml.etree import ElementTree
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
indent(subelem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = j
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = j
return elem
root = ElementTree.parse('/tmp/xmlfile').getroot()
indent(root)
ElementTree.dump(root)
下面是一个Python3解决方案,它消除了难看的换行符问题(大量空白),并且与大多数其他实现不同,它只使用标准库。
import xml.etree.ElementTree as ET
import xml.dom.minidom
import os
def pretty_print_xml_given_root(root, output_xml):
"""
Useful for when you are editing xml data on the fly
"""
xml_string = xml.dom.minidom.parseString(ET.tostring(root)).toprettyxml()
xml_string = os.linesep.join([s for s in xml_string.splitlines() if s.strip()]) # remove the weird newline issue
with open(output_xml, "w") as file_out:
file_out.write(xml_string)
def pretty_print_xml_given_file(input_xml, output_xml):
"""
Useful for when you want to reformat an already existing xml file
"""
tree = ET.parse(input_xml)
root = tree.getroot()
pretty_print_xml_given_root(root, output_xml)
我找到了如何修复常见的换行符问题在这里。
你有几个选择。
xml etree ElementTree。缩进()
包括电池,使用简单,输出漂亮。
但需要Python 3.9+
import xml.etree.ElementTree as ET
element = ET.XML("<html><body>text</body></html>")
ET.indent(element)
print(ET.tostring(element, encoding='unicode'))
BeautifulSoup.prettify ()
BeautifulSoup可能是Python < 3.9最简单的解决方案。
from bs4 import BeautifulSoup
bs = BeautifulSoup(open(xml_file), 'xml')
pretty_xml = bs.prettify()
print(pretty_xml)
输出:
<?XML版本="1.0"编码="utf-8"?> <问题> <问题> <标识> 1 < / id > <标题> 添加Visual Studio 2005和2008解决方案文件 < /名称> > < /问题 > < /问题
这是我要回答的。默认实参按原样工作。但是文本内容在单独的行上展开,就好像它们是嵌套的元素一样。
lxml.etree.parse()
更漂亮的输出,但是带有参数。
from lxml import etree
x = etree.parse(FILE_NAME)
pretty_xml = etree.tostring(x, pretty_print=True, encoding=str)
生产:
<问题> <问题> <标识> 1 > < / id <title>添加Visual Studio 2005和2008解决方案文件 <details>我们需要Visual Studio 2005/2008的Windows项目文件 > < /问题 > < /问题
这对我来说没什么问题。
xml dom minidom parse()。
没有外部依赖,只有后处理。
import xml.dom.minidom as md
dom = md.parse(FILE_NAME)
# To parse string instead use: dom = md.parseString(xml_string)
pretty_xml = dom.toprettyxml()
# remove the weird newline issue:
pretty_xml = os.linesep.join([s for s in pretty_xml.splitlines()
if s.strip()])
输出与上面相同,但是代码更多。