在变量中读取XML文件(带缩进)(使用Python)

时间:2014-08-13 21:30:12

标签: python xml file parsing indentation

有没有办法逐行读取XML文件,缩进Python变量?

我尝试了以下内容:

from lxml import etree as ET
tree = ET.parse("f1.xml")

from lxml import etree as ET
tree = ET.parse("f1.xml")
t1 = ET.fromstring(tree)

在做#2时,我收到以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lxml.etree.pyx", line 3032, in lxml.etree.fromstring (src/lxml/lxml.etree.c:68121)
  File "parser.pxi", line 1785, in lxml.etree._parseMemoryDocument (src/lxml/lxml.etree.c:102459)
ValueError: can only parse strings"

如果我使用fopen函数来读取XML文件,则会添加一大堆垃圾 - 因为它似乎使用Microsoft Word或Open Office来读取文件..

1 个答案:

答案 0 :(得分:-1)

import lxml.etree as etree 
x = etree.parse("filename") 
print etree.tostring(x, pretty_print = True)

这对我有用!