问题
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'?
回答1:
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>'
回答2:
- 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
来源:https://stackoverflow.com/questions/40244271/change-xml-element-text-using-xml-etree-elementtree