How to replace the text inside an XML element?

11,380

This is fairly easy with ElementTree. Just replace the value of the text attribute of your element:

>>> from xml.etree.ElementTree import parse, tostring
>>> doc = parse('file.xml')
>>> elem = doc.findall('original_spoken_locale')[0]
>>> elem.text = 'new-value'
>>> print tostring(doc.getroot())
<video>
    <original_spoken_locale>new-value</original_spoken_locale>
    <another_tag>somevalue</another_tag>
</video>

This is safer, too, since you can have en-US in another places of your document.

Share:
11,380
David542
Author by

David542

Updated on June 15, 2022

Comments

  • David542
    David542 almost 2 years

    Given the following xml:

    <!-- file.xml -->
    <video>
        <original_spoken_locale>en-US</original_spoken_locale>
        <another_tag>somevalue</another_tag>
    </video>
    

    What would be the best way to replace the value inside of the <original_spoken_locale> tag? If I did know the value, I could use something like:

    with open('file.xml', 'r') as file:
        contents = file.read()
    new_contents = contents.replace('en-US, 'new-value')
    with open('file.xml', 'w') as file:
        file.write(new_contents)
    

    However, in this case, I don't know what the value will be.