2012-06-22 44 views
2

考慮下面的XML:如何替換XML元素中的文本?

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

什麼是更換<original_spoken_locale>標籤內的值的最佳方法?如果我知道價值,我可以使用類似於:

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) 

但是,在這種情況下,我不知道該值是多少。

回答

8

這對ElementTree來說相當簡單。只需更換你的元素的text屬性的值:

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

這是更安全,也因爲你可以在你的文檔的其他地方en-US

+0

是否有R基礎解決方案? – RanonKahn