Python Forum
Replace XML tag and write to the same file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace XML tag and write to the same file
#4
Thanks Larz60+ & Snippsat. I'm able to pass through and new file is being generated with below code but this is deleting the comments which are already there in source xml file. Any thoughts on how to get the comments as well to the new file ?

import xml.etree.ElementTree as ET

def newidentity(filename):
   tree = ET.ElementTree(file=filename)
   root = tree.getroot()
   for id in root.iter('identity'):
       print id.text
       identity.text = "123456"
       tree = ET.ElementTree(root)
       print tree
   with open("newfile.xml", "wb") as somefile:
      tree.write(somefile)

if __name__ == "__main__":
   newidentity(filename)
Reply


Messages In This Thread
RE: Replace XML tag and write to the same file - by krish216 - Mar-25-2020, 09:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file? JohnJSal 13 28,756 Yesterday, 12:26 PM
Last Post: hanmen9527
Question [SOLVED] [Beautiful Soup] Replace tag.string from another file? Winfried 2 569 May-01-2025, 03:43 PM
Last Post: Winfried
  Replace values in Yaml file with value in dictionary PelleH 1 2,364 Feb-11-2025, 09:51 AM
Last Post: alexjordan
  How to write variable in a python file then import it in another python file? tatahuft 4 1,070 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  [SOLVED] [Linux] Write file and change owner? Winfried 6 1,790 Oct-17-2024, 01:15 AM
Last Post: Winfried
  What does .flush do? How can I change this to write to the file? Pedroski55 3 1,509 Apr-22-2024, 01:15 PM
Last Post: snippsat
  Last record in file doesn't write to newline gonksoup 3 1,755 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  write to csv file problem jacksfrustration 11 5,734 Nov-09-2023, 01:56 PM
Last Post: deanhystad
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 4,136 Nov-09-2023, 10:56 AM
Last Post: mg24
  Replace a text/word in docx file using Python Devan 4 25,020 Oct-17-2023, 06:03 PM
Last Post: Devan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020