修改xml文件中子节点的文本值并保存(使用python)

Modify the text value of child node in xml file and save it (using python)

我的 xml 文件是:

<annotation>
    <folder>cancer</folder>
    <filename>cancer1.jpg</filename>
    <path>/Volumes/Windows/tongue-img/cancer/cancer1.jpg</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>3088</width>
        <height>2056</height>
        <depth>3</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>cancer</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>1090</xmin>
            <ymin>869</ymin>
            <xmax>1807</xmax>
            <ymax>1379</ymax>
        </bndbox>
    </object>
</annotation>

我要更改子节点1090的文本值 通过对其执行一些算术运算(例如从中减去 10)来计算该值。 执行操作并更改值但未将其保存到 xml 文件,即 xml 文件未更新,它保持不变。 Python 代码是:

import xml.etree.ElementTree as ET

tree = ET.parse('/Users/sripdeep/Desktop/Tongue_Cancer/leuko32.xml')  
root = tree.getroot()
X=10
print (root[6][4][0].text)
v1=root[6][4][0].text
v1 = int(v1) - X
print('New:')
print (v1)

print (root[6][4][1].text)
print (root[6][4][2].text)
print (root[6][4][3].text)

tree.write(open('C1.xml'))

文件C1.xml未更新。

输出是(当 运行 python 打印值时):

Old text value:
1090
New text value:
1080
869
1807
1379

但是修改后的xml文件中的值仍然是1090

我想你要找的是修改文本。您已获得该值,但未在底层树中更改它。要更改为,您只需使用 = 运算符。

root[6][4][0].text = v1

您的最终代码如下所示:

import xml.etree.ElementTree as ET

tree = ET.parse('/Users/sripdeep/Desktop/Tongue_Cancer/leuko32.xml')  
root = tree.getroot()
X=10
print (root[6][4][0].text)
v1=root[6][4][0].text
v1 = int(v1) - X
print('New:')
print (v1)

root[6][4][0].text = str(v1)

print (root[6][4][1].text)
print (root[6][4][2].text)
print (root[6][4][3].text)

tree.write(open('C1.xml', 'w'))
import xml.etree.ElementTree as ET

tree = ET.parse('./sample.xml')  
root = tree.getroot()
X=10
print (root[6][4][0].text)
v1=root[6][4][0].text
v1 = int(v1) - X
print('New:')
print (v1)

root[6][4][0].text = str(v1)
print (root[6][4][1].text)
print (root[6][4][2].text)
print (root[6][4][3].text)

tree.write('C1.xml')