【发布时间】:2019-07-18 03:16:50
【问题描述】:
我的 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
【问题讨论】:
-
你能确认树已经改变了吗?
-
不,它没有改变原始文件保持不变
-
我指的是
tree。你能确认python中的对象发生了变化吗? -
局部变量的值被改变了,但在树中它没有,v1的值在python中改变而不是在树中
-
试试我的答案。我不是 100% 确定,但我认为它可能会奏效。
标签: python xml-parsing elementtree