Apr-07-2021, 06:58 PM
I'm trying to edit an xml but in the process I'm losing the formatting and thus the edited xml is not readable in the software I want to because of the messed formatting. I do not want to lose any formatting and just replace some simple text but in the process my formatting is getting lost. This is the kind of simple function I have. Please can anyone help so that my original xml formatting is retained?
def xml_parsing(file_name, tag_name, source_string_list, target_string_list): from xml.etree import ElementTree with open(file_name, 'rb+') as f: tree = ElementTree.parse(f) root = tree.getroot() element = root.find(tag_name) count = len(source_string_list) for x in range(count): element.text = element.text.replace(str(source_string_list[x]), (target_string_list[x])) tree.write(file_name, xml_declaration=True, encoding='utf-8')