我的程序基本上讀取一個輸入文件,從該文件中生成一個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>
上午在哪裏我弄錯了?我已經嘗試了很多解決方案,但似乎沒有任何工作(美麗,整潔,解析器...)
它可以與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) –
嗨,保羅,我正在嘗試你說,但是什麼是fp?我想寫的文件?對不起,我是初學者! – JAWE
只是表示要寫入的文件的文件指針,是的。 '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)' –