2013-07-18 80 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