Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replacing text in xml
#1
I have this code but the text is not replaced in the file titled: file_name (although as a python string the replacement is correct but I expected to change in file_name)

Can anyone figure why is that?

def xml_parsing(file_name, append_values, search_1, search_2):
    
    from xml.etree import ElementTree
    with open(file_name, 'rb+') as f:
        tree = ElementTree.parse(f)
        root = tree.getroot()
        
        root.find(search_1).text.replace("(VALUE)DS-L462-060901-C01-21(/VALUE)", "(VALUE)" + str(append_values[0]) + "(/VALUE)")

    tree.write(file_name, xml_declaration=True, encoding='utf-8') 
Reply
#2
I shall be extremely grateful if someone can help?
Reply
#3
You are calling replace() on a string. But that just returns the modified string, it doesn't change the original object.

>>> x = "foobar"
>>> x.replace("foo", "XX")
'XXbar'
>>> x
'foobar'
In your line 8, it is returning a value of the replaced text, but you are not capturing or doing anything with the value. In the meantime, root and the object that it points to are unmodified.

Probably something like:
        element = root.find(search_1)
        element.text = element.text.replace("(VALUE)DS-L462-060901-C01-21(/VALUE)", "(VALUE)" + str(append_values[0]) + "(/VALUE)")
ateestructural likes this post
Reply
#4
Thank you very much, that sorted it. Much appreciated and obliged
Reply
#5
Thankyou for sharing this
Reply


Forum Jump:

User Panel Messages

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