根据 Python 中的属性值从 XML 节点中删除节点

Remove node from XML node based an attribute value in Python

我正在尝试根据节点的属性值删除节点


from xml.etree import ElementTree as ET

groups = ET.fromstring("""<groups>
<group>
<group_components>
<id item="1">14742</id>
<id item="1">121727</id>
<id item="0">541971</id>
</group_components>
</group>
<group>
<group_components>
<id item="1">10186</id>
<id item="1">10553</id>
<id item="1">10644</id>
<id item="0">434639</id>
</group_components>
</group>
</groups>
""")


fnodes = groups.findall('group')
for first in fnodes:
    bnode = first.find("group_components")
    for child in bnode:
        items = child.attrib.get('item')
        if items == "1":
            bnode.remove(child)
            
xmlstr = ET.tostring(groups, encoding="utf-8", method="xml")
print(xmlstr.decode("utf-8"))                 
              

以上代码只是删除单个节点。如果属性项=1 那个id节点应该去掉

见下文

from xml.etree import ElementTree as ET

xml = """<groups>
<group>
    <group_components>
        <id item="1">14742</id>
        <id item="1">121727</id>
        <id item="0">541971</id>
    </group_components>
    </group>
<group>
    <group_components>
        <id item="1">10186</id>
        <id item="1">10553</id>
        <id item="1">10644</id>
        <id item="0">434639</id>
    </group_components>
</group>
</groups>
"""
root = ET.fromstring(xml)
for grp_comp in root.findall('.//group_components'):
    for _id in list(grp_comp):
        if _id.attrib['item'] == "1":
            grp_comp.remove(_id)
ET.dump(root)

输出

<groups>
<group>
    <group_components>
        <id item="0">541971</id>
    </group_components>
    </group>
<group>
    <group_components>
        <id item="0">434639</id>
    </group_components>
</group>
</groups>
to_remove = ['<id item="1">']
with open('xmlfile.xml') as xmlfile, open('newfile.xml', 'w') as newfile:
    for line in xmlfile:
        if not any(remo in line for remo in to_remove):
            newfile.write(line)

您可以放置​​ xml 文件并获取删除了 <id item="1"> 的新 xml 文件。我猜这里不需要元素树。