用Python打印XML的最佳方法(或各种方法)是什么?
当前回答
我用几行代码解决了这个问题,打开文件,通过它并添加缩进,然后再次保存它。我使用的是小的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()
这对我来说很有用,也许有人会用到它:)
其他回答
另一个解决方案是借用这个缩进函数,用于自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)
我看不懂迷你dom的漂亮印花。每当我尝试用给定编码之外的字符漂亮地打印文档时,我会得到一个UnicodeError,例如,如果我在文档中有一个β,我尝试了doc.toprettyxml(encoding='latin-1')。以下是我的解决方法:
def toprettyxml(doc, encoding):
"""Return a pretty-printed XML document in a given encoding."""
unistr = doc.toprettyxml().replace(u'<?xml version="1.0" ?>',
u'<?xml version="1.0" encoding="%s"?>' % encoding)
return unistr.encode(encoding, 'xmlcharrefreplace')
LXML是最近更新的,包含一个漂亮的打印函数
import lxml.etree as etree
x = etree.parse("filename")
print etree.tostring(x, pretty_print=True)
查看lxml教程: http://lxml.de/tutorial.html
下面是我解决难看的文本节点问题的解决方案。
uglyXml = doc.toprettyxml(indent=' ')
text_re = re.compile('>\n\s+([^<>\s].*?)\n\s+</', re.DOTALL)
prettyXml = text_re.sub('>\g<1></', uglyXml)
print prettyXml
上面的代码将产生:
<?xml version="1.0" ?>
<issues>
<issue>
<id>1</id>
<title>Add Visual Studio 2005 and 2008 solution files</title>
<details>We need Visual Studio 2005/2008 project files for Windows.</details>
</issue>
</issues>
而不是这样:
<?xml version="1.0" ?>
<issues>
<issue>
<id>
1
</id>
<title>
Add Visual Studio 2005 and 2008 solution files
</title>
<details>
We need Visual Studio 2005/2008 project files for Windows.
</details>
</issue>
</issues>
免责声明:可能有一些限制。
从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