byemute
byemute

Reputation: 653

Python Minidom modify/append content files

Since 8 hours I'm now trying to parse a XML and add 5 lines of text into the xml. I'm making really no progress and neither writexml, toxml nor saveXML seems to work from the minidom lib

We want to parse the xml and add some lines before the closing Tag. Sounds easy?

So my situation is: A File called updates.xml

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

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

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

What we are doing:

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 contains the correct new lines, but the file just isn't updated. Can anyone explain this?

Upvotes: 2

Views: 4425

Answers (1)

alecxe
alecxe

Reputation: 473853

Parse the document, get UpdateSite node, append a Text node to it. Then pass an opened file to the 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)

produces the following xml:

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

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

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

Hope that helps.

Upvotes: 2

Related Questions