问题
I have an XML file and I need to replace the value that comes right after "type" with a value from a vector v=[7,8,9]
using a Python code. I need the code to recognize the word "type" and then change the value of the parameter in the following line. The value 2 should be replaced by v[0]
, 3 by v[1]
and so on. Is there a way to do this with ElementTree or with readlines?
<Model>
<Function>
<param>x</param>
<param>type</param>
<param>2</param>
<param>5</param>
</Function>
<Function>
<param>y</param>
<param>type</param>
<param>3</param>
<param>2</param>
</Function>
<Function>
<param>z</param>
<param>type</param>
<param>7</param>
<param>9</param>
</Function>
</Model>
回答1:
we can change values using the module xml.etree.ElementTree
.
In code child represents Function
tag and child[x] represents x
th element in the Function
tag.By using text
attribute we can access values of elements.
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
v = [7, 8, 9]
for child in root:
child[2].text = str(v.pop(0))
tree.write('output.xml')
Another Approach:
we can also solve by comparing the elements, if element text is equal to type
then we update the value next to it.
elements = root.findall('Function/param')
for i in range(len(elements)):
if elements[i].text == 'type':
elements[i + 1].text = str(v.pop(0))
tree.write('output.xml')
来源:https://stackoverflow.com/questions/60429621/replace-values-in-xml-file-with-values-of-a-vector