Eddwinn Eddwinn - 3 months ago 10
Python Question

Python writing to an xml file

I am trying to write to an xml file. I have changed a specific element in my code, and am able to get it to print successfully. I need to have it written to the file, without changing the structure of the file.

My code:

import os
from lxml import etree

directory = '/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT'
XMLParser = etree.XMLParser(remove_blank_text=True)
for f in os.listdir(directory):
if f.endswith(".xml"):

xmlfile = directory + '/' + f



tree = etree.parse(xmlfile, parser=XMLParser)
root = tree.getroot()

hardwareRevisionNode = root.find(".//hardwareRevision")



if hardwareRevisionNode.text == "5":
print " "
print "Old Tag: " + hardwareRevisionNode.text

x = hardwareRevisionNode.text = "DVT2"

print "New Tag " + hardwareRevisionNode.text


When I try various methods of opening and closing the file, it just deletes all the data in the xml file. Using this method

outfile = open(xmlfile, 'w')
oufile.write(etree.tostring(tree))
outfile.close()


Changed the code structure of my file to be one long line.

Answer

If you are wanting to replace a value within an existing XML file then use:

tree.write(xmlfile) 

Currently you are simply overwriting your file entirely and using the incorrect method (open()). tree.write() is normally what you would want to use. It might look something like this:

tree = etree.parse(xmlfile, parser=XMLParser)
root = tree.getroot()
hardwareRevisionNode = root.find(".//hardwareRevision")
if hardwareRevisionNode.text == "5":
    print "Old Tag: " + hardwareRevisionNode.text
    hardwareRevisionNode.text = "DVT2"
    print "New Tag: " +  hardwareRevisionNode.text
    tree.write(xmlfile)

https://docs.python.org/2/library/xml.etree.elementtree.html

Comments