XML在Python中从文件中进行预处理

时间:2015-04-20 21:29:39

标签: python xml prettify

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

许多文本包含空格作为起始字符,或者在开头有\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

1 个答案:

答案 0 :(得分:2)

bs4可以做到

from bs4 import BeautifulSoup

doc = BeautifulSoup(xmlstring, 'xml')

print doc.prettify()