Frank Frank - 3 months ago 7
Python Question

Alter Existing Text in XML Using etree

I have the following XML:

<root>
<element>
<subelement1>
subelement1 text
</subelement1>
<subelement2>
subelement2 text
</subelement2>
</element>
</root>


It's my goal to parse the tree, and alter only the data in a particular subelement, in this case
<subelement2>
.So, where currently there exists the string
subelement2 text
, I want to be able to append data to that so that the resulting XML is as follows:

<root>
<element>
<subelement1>
subelement1 text
</subelement1>
<subelement2>
subelement2 text + my new string of text
</subelement2>
</element>
</root>


Noting, that
subelement2 text
has now become
subelement2 text + my new string of text


What I am looking for help in understanding, is the general function or approach used to alter existing text within a subelement, as in the example above.

Answer

Simply assign to the text attribute of the relevant element:

el = doc.find('.//subelement2')
el.text += ' + my new string of text'