0

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.

Community
  • 1
  • 1
Anekdotin
  • 1,531
  • 4
  • 21
  • 43
  • Unrelated to your question, but you can make your code a bit simpler by using the [`glob` module](https://docs.python.org/2/library/glob.html). – Tomalak Aug 26 '16 at 16:11
  • Perhaps for future audiences, you could show a better way. The point of stackoverflow is to build a library of knowledge for improvement in coding. Plus im curious :) – Anekdotin Aug 26 '16 at 16:13
  • `xmlfiles = glob('/Users/eeamesX/work/data/expert/EFTlogs/20160725/IT/*.xml')` – Tomalak Aug 26 '16 at 16:14

1 Answers1

2

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!

derelict
  • 2,044
  • 10
  • 15
  • It was the = sign, as stated in your first part of your answer. Thank you sir. Im so used to writing == – Anekdotin Aug 26 '16 at 16:07