Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 631
category Avatar asked Oct 25 '16 15:10

category


People also ask

What is XML Etree ElementTree in Python?

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.


2 Answers

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>'
like image 51
alecxe Avatar answered Oct 04 '22 19:10

alecxe


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

like image 33
shaz Avatar answered Oct 04 '22 20:10

shaz