【问题标题】:Remove the xml tag if the childnode text value is 'None'如果子节点文本值为“无”,则删除 xml 标记
【发布时间】:2019-12-02 02:33:46
【问题描述】:

如果 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 文件中删除特定的 &lt;object&gt; 标记。我试过代码:

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

【问题讨论】:

    标签: python python-3.x elementtree


    【解决方案1】:
    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'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      相关资源
      最近更新 更多