11

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

2 Answers 2

26

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>'
Sign up to request clarification or add additional context in comments.

1 Comment

So simple, it's a shame the docs entry for "text" has nothing written there. It could at least mention it is a string.
1
import xml.etree.ElementTree as et # import the elementtree module
root = et.fromstring(command_request) # fromString parses xml from string to an element, command request can be xml request string
root.find("cat").text = "dog" #find the element tag as cat and replace it with the string to be replaced.
et.tostring(root) # converts the element to a string

cheers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.