1

I am trying to remove a node based on it's attribute value


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

The above code is only removing single node. If the attribute item =1 that id node should be removed

1
  • which elements should be removed? Commented Aug 23, 2021 at 11:55

2 Answers 2

2

See below

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)

output

<groups>
<group>
    <group_components>
        <id item="0">541971</id>
    </group_components>
    </group>
<group>
    <group_components>
        <id item="0">434639</id>
    </group_components>
</group>
</groups>
Sign up to request clarification or add additional context in comments.

Comments

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

You can put your xml file and get the new xml file with <id item="1"> removed. No need of element tree here I guess.

1 Comment

Looks great and handy but the solution provided by @balderman is apt for my project. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.