0

Hello how I can remove element using Python's ElementTree.fromstring.

I want to remove the entire "cpu block" from the following xml, would you please help me.

<domain type='kvm'>
  <name>udraz</name>
  <uuid>a62e21b0-2111-421e-a27f-1bc7f6b3c46f</uuid>
  <description>My VM</description>
  <memory unit='KiB'>1048576</memory>
  <currentMemory unit='KiB'>1048576</currentMemory>
  <vcpu placement='static'>4</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-rhel7.0.0'>hvm</type>
    <boot dev='cdrom'/>
    <boot dev='hd'/>
    <bootmenu enable='yes'/>
  </os>
  <features>
    <acpi/>
    <apic/>
    <pae/>
  </features>
  <cpu mode='custom' match='exact'>
    <model fallback='allow'>Nehalem</model>
  </cpu>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>restart</on_crash>
</domain>

2 Answers 2

1

You can do it with Element.remove method like so:

from xml.etree import ElementTree

root = ElementTree.fromstring(your_xml_string)    
for elem in root.findall("cpu"):
    root.remove(elem)
Sign up to request clarification or add additional context in comments.

Comments

0

This will remove all elements with tag "cpu"

from xml.etree import ElementTree as et
tree = et.fromstring(xml)
[ tree.remove(elem) for elem in tree.iter() if elem.tag=="cpu"]

if you want remove all elements with any mentions with "cpu" in tag you should use if elem.tag in "cpu"

Comments

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.