2013-07-18 78 views
5

我的程序基本上读取一个输入文件,从该文件中生成一个lxml.etree,比如我向etree添加一个节点,然后我想将它打印回文件。 所以将它写回我用一个文件:使用lxml格式化输出为XML

et.write('Documents\Write.xml', pretty_print=True) 

和输出我是:

<Variable Name="one" RefID="two"><Component Type="three"><Value>four</Value></Component></Variable> 

虽然我想是这样的:

<Variable Name="one" RefID="two"> 
    <Component Type="three"> 
     <Value>four</Value> 
    </Component> 
</Variable> 

上午在哪里我弄错了?我已经尝试了很多解决方案,但似乎没有任何工作(美丽,整洁,解析器...)

+0

它可以与Windows相关吗?如果你尝试使用'io'模块打开你的输出文件:'fp = io.open('Documents \ Write.xml','w',newline ='\ r \ n') 然后'写入'fp ''就像'et.write(fp,pretty_print = True)' (见http://docs.python.org/2/library/io.html#io.open) –

+0

嗨,保罗,我正在尝试你说,但是什么是fp?我想写的文件?对不起,我是初学者! – JAWE

+0

只是表示要写入的文件的文件指针,是的。 'et.write()'可以将一个文件名或一个打开的文件指针作为输入,就像来自'io.open'的东西(http://lxml.de/api/lxml.etree._ElementTree-class.html#write )。你可以尝试'导入io',然后'et.write(io.open('Documents \ Write.xml','w',newline ='\ r \ n'),pretty_print = True)' –

回答

1

这很奇怪,因为它正是它的工作方式。 你能试试这个:

root = etree.XML(YOUR XML STRING) 
print etree.tostring(root, pretty_print=True) 

<Variable Name="one" RefID="two"> 
    <Component Type="three"> 
    <Value>four</Value> 
    </Component> 
</Variable> 

这应该产生一个格式化的字符串,它可以处理自己。

+1

感谢您的答案,但那是我的方式。并以这种方式工作,但它不会当我写在一个文件中..我不知道为什么!不管怎么说,还是要谢谢你。 – JAWE

+0

我也是这样做,但遇到同样的问题,因为@JAWE – adubey

2

请勿使用标准解析器。 使用remove_blank_text = True的自定义分析器。

parser = etree.XMLParser(remove_blank_text=True) 
tree = etree.parse(self.output_file, parser=parser) 
// Do stuff with the tree here 
tree.write(your_output_file, pretty_print=True) 
+0

我有同样的问题,这对我来说,同样的答案在这里:http://stackoverflow.com/questions/7903759/pretty-print-in- LXML-IS-失败 - 当 - 我加标签到一个解析的树 – cptPH