Python Forum
XML Editing formatting lost - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: XML Editing formatting lost (/thread-33229.html)



XML Editing formatting lost - ateestructural - Apr-07-2021

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') 



RE: XML Editing formatting lost - ateestructural - Apr-07-2021

I shall be extremely grateful if someone can help as I'm really stressed up with this


RE: XML Editing formatting lost - ndc85430 - Apr-08-2021

What formatting is being lost? It might help of you showed a sample XML document.