Eddwinn Eddwinn - 3 months ago 11
Python Question

Python Changing value of XML

Hello im using lxml to try and change the value of a specific xml element. Here is my code.

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 hardwareRevisionNode.text
str(hardwareRevisionNode.text) == "DVT3"
print hardwareRevisionNode.text


I want to change the 5 to a DVT3 instead it just prints it out below as 5 and 5. I referenced Change xml using python . Unfortunately it doesnt work for me.

Answer

looks like you need assignment = not comparison == and the cast to string str() is unnecessary. once you've assigned the value, you'll want to write the result back out to the file:

hardwareRevisionNode.text = "DVT3"

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

good luck!