繁体   English   中英

如果childnode文本值为“ None”,则删除xml标记

[英]Remove the xml tag if the childnode text value is 'None'

如果xmin,ymin,xmax,ymax的值为None ,我想删除整个<object>标记。 xml文件是:

<annotation>
    <folder>leuko</folder>
    <filename>leuko32.jpg</filename>
    <path>/Volumes/Windows/tongue-img/leuko/leuko32.jpg</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>3456</width>
        <height>2304</height>
        <depth>3</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>leuko</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>1329</xmin>
            <ymin>671</ymin>
            <xmax>1941</xmax>
            <ymax>1252</ymax>
        </bndbox>
    </object>
    <object>
        <name>leuko</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>None</xmin>
            <ymin>671</ymin>
            <xmax>1941</xmax>
            <ymax>1252</ymax>
        </bndbox>
    </object>
</annotation>

在这里,您可以看到xmin text的值为None,然后应在更新的xml文件中删除特定的<object>标记。 我尝试了代码:

import xml.etree.ElementTree as ET
tree = ET.parse(original_xml)  
root = tree.getroot()
removeList = list()
for child in tree.iter('object'):
    if child.tag == 'bndbox':
        name = child.find('xmin').text
        if (name == None):
            removeList.append(child)

for tag in removeList:
    parent = tree.find('object')
    parent.remove(tag)

tree.write(open(os.path.join(newxml_path , 'stomatitis427-2'), 'wb'))
import xml.etree.ElementTree as ET
tree = ET.parse(original_xml)  
root = tree.getroot()
value='-1'
objects = root.findall('object')
for object in objects:
        xmin1 = object.find('./bndbox/xmin')
        ymin1 = object.find('./bndbox/ymin')
        xmax1 = object.find('./bndbox/xmax')
        ymax1 = object.find('./bndbox/ymax')
        if value in xmin1.text:
            root.remove(object)
        if value in ymin1.text:
            root.remove(object)
        if value in xmax1.text:
            root.remove(object)
        if value in ymax1.text:
            root.remove(object)
tree.write(open(os.path.join(newxml_path , 'stomatitis427-2'), 'wb'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM