用Python打印XML的最佳方法(或各种方法)是什么?
当前回答
用于将整个xml文档转换为漂亮的xml文档 (例如:假设你已经解压缩了一个LibreOffice Writer .odt或.ods文件,你想把这个丑陋的“content.xml”文件转换成一个漂亮的文件,用于自动化git版本控制和git的。odt/。ods文件,比如我在这里实现的)
import xml.dom.minidom
file = open("./content.xml", 'r')
xml_string = file.read()
file.close()
parsed_xml = xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = parsed_xml.toprettyxml()
file = open("./content_new.xml", 'w')
file.write(pretty_xml_as_string)
file.close()
引用: -感谢本·诺兰德在本页上的回答,让我有了大部分的了解。
其他回答
如果你使用的是DOM实现,每一个都有自己的内置漂亮打印形式:
# minidom
#
document.toprettyxml()
# 4DOM
#
xml.dom.ext.PrettyPrint(document, stream)
# pxdom (or other DOM Level 3 LS-compliant imp)
#
serializer.domConfig.setParameter('format-pretty-print', True)
serializer.writeToString(document)
如果您正在使用其他没有自己的漂亮打印机的东西——或者那些漂亮打印机不能完全按照您想要的方式来做——您可能必须编写或子类化您自己的序列化器。
如果你有xmllint,你可以生成一个子进程并使用它。xmllint——format <file>将其输入的XML漂亮地打印到标准输出。
注意,这个方法使用了python之外的程序,这使得它有点像黑客。
def pretty_print_xml(xml):
proc = subprocess.Popen(
['xmllint', '--format', '/dev/stdin'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
(output, error_output) = proc.communicate(xml);
return output
print(pretty_print_xml(data))
我用几行代码解决了这个问题,打开文件,通过它并添加缩进,然后再次保存它。我使用的是小的xml文件,不想添加依赖项,也不想为用户安装更多的库。总之,这是我最后得出的结论:
f = open(file_name,'r')
xml = f.read()
f.close()
#Removing old indendations
raw_xml = ''
for line in xml:
raw_xml += line
xml = raw_xml
new_xml = ''
indent = ' '
deepness = 0
for i in range((len(xml))):
new_xml += xml[i]
if(i<len(xml)-3):
simpleSplit = xml[i:(i+2)] == '><'
advancSplit = xml[i:(i+3)] == '></'
end = xml[i:(i+2)] == '/>'
start = xml[i] == '<'
if(advancSplit):
deepness += -1
new_xml += '\n' + indent*deepness
simpleSplit = False
deepness += -1
if(simpleSplit):
new_xml += '\n' + indent*deepness
if(start):
deepness += 1
if(end):
deepness += -1
f = open(file_name,'w')
f.write(new_xml)
f.close()
这对我来说很有用,也许有人会用到它:)
你可以试试这种变化……
安装BeautifulSoup和后端lxml(解析器)库:
user$ pip3 install lxml bs4
处理XML文档:
from bs4 import BeautifulSoup
with open('/path/to/file.xml', 'r') as doc:
for line in doc:
print(BeautifulSoup(line, 'lxml-xml').prettify())
LXML是最近更新的,包含一个漂亮的打印函数
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print=True)
查看lxml教程: http://lxml.de/tutorial.html