XML 从 Python 中的文件美化

XML Prettifying from file in Python

我有一个 xml 文件,如下例所示。

许多文本包含 space 作为起始字符,或以 \n(换行符)开头,或其他疯狂的东西。我正在使用 xml.etree.ElementTree,从这个文件中解析是很好的。

但我想要更多! :) 我试图美化这个烂摊子,但没有成功。尝试了很多教程,但总是没有漂亮地结束XML。

<?xml version="1.0"?>
<import>
<article>
<name> Name with space
</name>
<source> Daily Telegraph
</source>
<number>72/2015
</number>
<page>10
</page>
<date>2015-03-26
</date>
<author> Tomas First
</author>
<description>Economy
</description>
<attachment>
</attachment>
<region>
</region>
<text>
 My text is here
</text>
</article>
<article>
<name> How to parse
</name>
<source> Internet article
</source>
<number>72/2015
</number>
<page>1
</page>
<date>2015-03-26
</date>
<author>Some author
</author>
<description> description
</description>
<attachment>
</attachment>
<region>
</region>
<text>
 My text here
</text>
</article>
</import>

当我尝试来自 SO 的另一个答案时,它生成相同的文件或更混乱的文件 XML

bs4可以做到

from bs4 import BeautifulSoup

doc = BeautifulSoup(xmlstring, 'xml')

print doc.prettify()