首页 > 解决方案 > 查找和替换 xml 子标签文本的 Python 代码

问题描述

我在下面有一个 xml 文件,我需要通过添加 10 或对其执行一些算术运算来查找和替换 xmin、ymin、xmax、ymax 标签。我是带有 xml 文件的 python 新手。

xml文件如下:

    <annotation>
    <folder>stomatitis</folder>
    <filename>stomatitis427.jpg</filename>
    <path>/Volumes/Windows/tongue-img/stomatitis/stomatitis427.jpg</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>2992</width>
        <height>2000</height>
        <depth>3</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>stomatitis</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>1324</xmin>
            <ymin>677</ymin>
            <xmax>1404</xmax>
            <ymax>783</ymax>
        </bndbox>
    </object>
    <object>
        <name>stomatitis</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>1610</xmin>
            <ymin>643</ymin>
            <xmax>1670</xmax>
            <ymax>720</ymax>
        </bndbox>
    </object>
</annotation>

我需要替换所有 xmin、ymin、xmax、ymax 标签文本值并保存更新的 xml 文件。我试过这段代码,但它给出了错误:

    import xml.etree.ElementTree as ET
        tree = ET.parse('/Users/sripdeep/Desktop/Tongue_Cancer/leuko32.xml')  
        root = tree.getroot()
        x=10
        n_xmin=str(xmin-x)
        n_ymin=str(ymin-x)
        n_xmax=str(xmax-x)
        n_ymax=str(ymax-x)
        for elem in root.getiterator():
            try:
                elem.text = elem.text.replace(str(xmin),n_xmin)
                elem.text = elem.text.replace(str(ymin),n_ymin)
                elem.text = elem.text.replace(str(xmax),n_xmax)
                elem.text = elem.text.replace(str(ymax),n_ymax)
            except AttributeError:
                pass
        tree.write(open('C2.xml', 'wb'))

新创建的 xml 文件中的值不会更新。

我也试过这段代码:

import xml.etree.ElementTree as ET

tree = ET.parse('/Users/sripdeep/Desktop/Tongue_Cancer/leuko32.xml')  
root = tree.getroot()
for i in root:
    print (i.find("xmin").text)

这也给出了错误:

print (i.find("xmin").text)

AttributeError: 'NoneType' object has no attribute 'text'

标签: python-3.xelementtree

解决方案


在第一个代码片段中,您使用未定义的变量,例如xminin n_xmin=str(xmin-x)

在第二个片段中,您尝试找到xmin根的每个孩子的孩子。XML 文档中不存在此类元素。xmin元素位于层次结构的更下方。


以下代码将 10 添加到xminyminxmaxymax元素的整数值。

import xml.etree.ElementTree as ET

tree = ET.parse('leuko32.xml')  

wanted = ["xmin", "ymin", "xmax", "ymax"]

for elem in tree.iter():
    if elem.tag in wanted:
        elem.text = str(int(elem.text) + 10)

tree.write('C2.xml')

推荐阅读