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'?
The xml. etree. ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.
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>'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With