Frank Frank - 3 months ago 8
Python Question

Alter existing text in etree Element object

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





I already can find parse the text and find
subelement2
, like so:

import xml.etree.ElementTree as ET
doc = ET.fromstring('''
<root>
<element>
<subelement1>
subelement1 text
</subelement1>
<subelement2>
subelement2 text
</subelement2>
</element>
</root>
''')
el = doc.find('.//subelement2')


...but once I have the Element object assigned to
el
, how do I alter its 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'
Comments