如何修改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>