用向量的值替换XML文件中的值 [英] Replace values in XML file with values of a vector
问题描述
我有一个XML文件,我需要使用Python代码用向量v=[7,8,9]
中的值替换类型"之后的值.我需要代码来识别单词"type",然后在下一行中更改参数的值.值2应替换为v[0]
,3应替换为v[1]
,依此类推.有没有办法用ElementTree或readlines做到这一点?
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>
推荐答案
我们可以使用模块xml.etree.ElementTree
更改值.
在代码中,child表示Function
标记,child [x]表示Function
标记中的x
th 元素.通过使用text
属性,我们可以访问元素的值.
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')
另一种方法:
我们还可以通过比较元素来解决,如果元素文本等于type
,则我们更新其旁边的值.
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')
这篇关于用向量的值替换XML文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!