Search code examples
pythonxmltextelement

change xml element text using xml.etree.ElementTree


Given a parsed xml string:

tree = xml.etree.ElementTree.fromstring(xml_string)

How would you change an element's text from 'hats':

>>> tree.find("path/to/element").text
>>> 'hats'

to 'cats'?


Solution

  • Simply set the .text attribute value:

    In [1]: import xml.etree.ElementTree as ET
    
    In [2]: root = ET.fromstring("<root><elm>hats</elm></root>")
    
    In [3]: elm = root.find(".//elm")
    
    In [4]: elm.text
    Out[4]: 'hats'
    
    In [5]: elm.text = 'cats'
    
    In [6]: ET.tostring(root)
    Out[6]: '<root><elm>cats</elm></root>'