使用 xml.etree.ElementTree 更改 xml 元素文本
change xml element text using xml.etree.ElementTree
给定一个已解析的 xml 字符串:
tree = xml.etree.ElementTree.fromstring(xml_string)
您将如何更改来自 'hats' 的元素的文本:
>>> tree.find("path/to/element").text
>>> 'hats'
到'cats'?
只需设置 .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
干杯
给定一个已解析的 xml 字符串:
tree = xml.etree.ElementTree.fromstring(xml_string)
您将如何更改来自 'hats' 的元素的文本:
>>> tree.find("path/to/element").text
>>> 'hats'
到'cats'?
只需设置 .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
干杯