用Python打印XML的最佳方法(或各种方法)是什么?
当前回答
LXML是最近更新的,包含一个漂亮的打印函数
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print=True)
查看lxml教程: http://lxml.de/tutorial.html
其他回答
使用etree。缩进和etree.tostring
import lxml.etree as etree
root = etree.fromstring('<html><head></head><body><h1>Welcome</h1></body></html>')
etree.indent(root, space=" ")
xml_string = etree.tostring(root, pretty_print=True).decode()
print(xml_string)
输出
<html>
<head/>
<body>
<h1>Welcome</h1>
</body>
</html>
删除名称空间和前缀
import lxml.etree as etree
def dump_xml(element):
for item in element.getiterator():
item.tag = etree.QName(item).localname
etree.cleanup_namespaces(element)
etree.indent(element, space=" ")
result = etree.tostring(element, pretty_print=True).decode()
return result
root = etree.fromstring('<cs:document xmlns:cs="http://blabla.com"><name>hello world</name></cs:document>')
xml_string = dump_xml(root)
print(xml_string)
输出
<document>
<name>hello world</name>
</document>
正如其他人指出的那样,lxml内置了一个漂亮的打印机。
请注意,在默认情况下,它会将CDATA部分更改为普通文本,这可能会产生糟糕的结果。
下面是一个Python函数,它保留输入文件,只改变缩进(注意strip_cdata=False)。此外,它确保输出使用UTF-8作为编码,而不是默认的ASCII(注意encoding=' UTF-8 '):
from lxml import etree
def prettyPrintXml(xmlFilePathToPrettyPrint):
assert xmlFilePathToPrettyPrint is not None
parser = etree.XMLParser(resolve_entities=False, strip_cdata=False)
document = etree.parse(xmlFilePathToPrettyPrint, parser)
document.write(xmlFilePathToPrettyPrint, pretty_print=True, encoding='utf-8')
使用示例:
prettyPrintXml('some_folder/some_file.xml')
from yattag import indent
pretty_string = indent(ugly_string)
它不会在文本节点中添加空格或换行,除非你要求它:
indent(mystring, indent_text = True)
您可以指定缩进单位和换行符的样式。
pretty_xml_string = indent(
ugly_xml_string,
indentation = ' ',
newline = '\r\n'
)
该文件在http://www.yattag.org主页上。
下面是一个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)
我找到了如何修复常见的换行符问题在这里。
我试图编辑上面“ade”的回答,但在我最初匿名提供反馈后,Stack Overflow不让我编辑。这是一个bug较少的函数版本,用于漂亮地打印一个ElementTree。
def indent(elem, level=0, more_sibs=False):
i = "\n"
if level:
i += (level-1) * ' '
num_kids = len(elem)
if num_kids:
if not elem.text or not elem.text.strip():
elem.text = i + " "
if level:
elem.text += ' '
count = 0
for kid in elem:
indent(kid, level+1, count < num_kids - 1)
count += 1
if not elem.tail or not elem.tail.strip():
elem.tail = i
if more_sibs:
elem.tail += ' '
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
if more_sibs:
elem.tail += ' '
推荐文章
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 当使用代码存储库时,如何引用资源的相对路径
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?