【问题标题】:Modify the text value of child node in xml file and save it (using python)修改xml文件中子节点的文本值并保存(使用python)
【发布时间】: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


【解决方案1】:

我认为您正在寻找的是修改文本。您已获得该值,但未在基础树中更改它。要更改为,您只需使用 = 运算符。

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'))

【讨论】:

  • 它给出了以下错误:无法序列化 %r (type %s)" % (text, type(text).__name__) TypeError: cannot serialize 1080 (type int)
【解决方案2】:
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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多