Page 1 of 1
Write to XML File
Posted: Tue Apr 05, 2011 6:18 pm
by kalia
I am trying to write a script that will update an existing xml file with a new element (derived from eg.result). I was looking at the File Operations plugin but concluded that this would not work (have to add the entry before the end tag of file). Can anyone help with this. Thanks.
Re: Write to XML File
Posted: Tue Apr 19, 2011 6:35 am
by Pako
Please attach a sample XML file and also how to be an additional element incorporated (into which the node).
Then I can better advise.
Pako
Re: Write to XML File
Posted: Thu Apr 21, 2011 4:22 am
by kalia
Attached is a sample xml file.
I want to update this file to add the following lines
before the last line ("</PayloadsRoot>"):
Code: Select all
<payload>
<value>test3</value>
<phrase>test3</phrase>
</payload>
The value "test3" is going to be from an Eventghost variable {eg.result}.
Thank you Pako for replying.
Re: Write to XML File
Posted: Thu Apr 21, 2011 8:09 am
by Pako
Here is a script:
Code: Select all
filePath = r"D:\Data\sample.xml"
from xml.dom import minidom as miniDom
from codecs import lookup
xmldoc = miniDom.parse(filePath)
document = xmldoc.getElementsByTagName('PayloadsRoot')
payloadNode = xmldoc.createElement(u'payload')
for item in (u'value', u'phrase'):
itemNode = xmldoc.createElement(item)
itemText = xmldoc.createTextNode(unicode(eg.result))
itemNode.appendChild(itemText)
payloadNode.appendChild(itemNode)
document[0].appendChild(payloadNode)
f = file(filePath, "wb")
writer = lookup('utf-8')[3](f)
xmldoc.writexml(writer, encoding = 'utf-8')
f.close()
Pako
Re: Write to XML File
Posted: Fri Apr 22, 2011 6:17 am
by kalia
Thank you Pako for your help. I would not have figured that out on my own (my Google search was way off).
The script worked fine. I am going to try to find out if the output can be formatted properly (the script writes new entry unformatted without tabs and line feeds).
Re: Write to XML File
Posted: Fri Apr 22, 2011 10:59 am
by Pako
kalia wrote:I am going to try to find out if the output can be formatted properly (the script writes new entry unformatted without tabs and line feeds).
Usually it is not necessary. To view the contents of a xml file is much better to use the XML Notepad.
But if you really need it, take a look
here.
Pako