David542
David542

Reputation: 110163

How to replace the text inside an XML element?

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.

Upvotes: 2

Views: 11678

Answers (1)

brandizzi
brandizzi

Reputation: 27050

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.

Upvotes: 8

Related Questions