如何修改xml文件中child的内部文本



如何在XML文件中修改子项的内部文本?有人能通过代码片段给我举个例子吗?我正在使用Python。

示例:

<?xml version="1.0" encoding="UTF-8"?>
<dictionary>
<!--GUI-Parameter-->
<item>
<key typ="str">WindowTop</key>
<value typ="int">20</value><!--[Pix]-->
</item>
<item>
<key typ="str">WindowLeft</key>
<value typ="int">20</value><!--[Pix]-->
</item>

在这里,我想将键WindowTop的值从20修改为40。

您可以使用xpath找到元素,然后使用text属性更改值

import xml.etree.ElementTree as ET
tree = ET.parse('data.xml')
root = tree.getroot()
elmt = root.find('.//item[key="WindowTop"]/value')
if elmt is not None:
elmt.text = str(40)
tree.write('output.xml')

输出:

<dictionary>

<item>
<key typ="str">WindowTop</key>
<value typ="int">40</value>

</item>
<item>
<key typ="str">WindowLeft</key>
<value typ="int">20</value>

</item>
</dictionary>

最新更新