2014-03-13 118 views
2

由於存在8個小時,我現在我試圖解析一個xml並添加5行文字到XML。我正在真的沒有進步,沒有中WriteXML,也不toxml用於似乎saveXML從minidom命名工作的libPython的minidom命名修改/添加內容文件

我們需要解析的XML和結束標記前添加一些行。聽起來很容易?

所以我的情況是: 稱爲updates.xml

<UpdateSite> 
    <SomeTags></SomeTags> 
    <SomeTags2></SomeTags2> 
    <SomeTags3></SomeTags3> 

    <SomeTags></SomeTags> 
    <SomeTags2></SomeTags2> 
    <SomeTags3></SomeTags3> 

    <SomeTags></SomeTags> 
    <SomeTags2></SomeTags2> 
    <SomeTags3></SomeTags3> 
</UpdateSite> 

我們正在做的一個文件:

dom = xml.dom.minidom.parse("updates.xml") 
updateSite=dom.getElementsByTagName('UpdateSite') 
updateSite.append('<SomeTags>') 
updateSite.append("<product>xx.xxxxxx.xxx</product>") 
updateSite.append("<version style=\\"eclipse\\">"+$cleanVersion+"</version>") 
updateSite.append("<resource style=\\"executable\\">SomeURL</resource>) 
updateSite.append("</update>") 
dom.saveXML(self, updateSite) 
dom.writeXML(self, file_handle) 
dom.toxml(self) 

回到updateSite包含正確的新的生產線,但該文件只沒有更新。任何人都可以解釋嗎?

回答

2

解析文檔,得到UpdateSite節點,一個節點Text追加到它。然後打開的文件傳遞給dom.writexml()

from xml.dom.minidom import parse, Text 

dom = parse("updates.xml") 

updateSite = dom.getElementsByTagName('UpdateSite')[0] 
text = Text() 
text.data = 'test' 
updateSite.appendChild(text) 

with open("new_updates.xml", "wb") as f: 
    dom.writexml(f) 

產生下面的XML:

<?xml version="1.0" ?><UpdateSite> 
    <SomeTags/> 
    <SomeTags2/> 
    <SomeTags3/> 

    <SomeTags/> 
    <SomeTags2/> 
    <SomeTags3/> 

    <SomeTags/> 
    <SomeTags2/> 
    <SomeTags3/> 
test</UpdateSite> 

希望有所幫助。

+0

我們要寫入同一個文件,我們看過了,這可能嗎? – byemute

+0

@byemute肯定的是,剛剛從'new_updates.xml'將名稱更改爲'updates.xml'。 – alecxe

+0

明天我會試試。放棄了現在,我很沮喪^^ – byemute