如何使用ElementTree.fromstring删除元素

时间:2016-12-12 06:08:37

标签: python xml

您好我如何使用Python的ElementTree.fromstring删除元素。

我想从以下xml中删除整个“cpu block”,请你帮忙。

<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 个答案:

答案 0 :(得分:1)

您可以使用Element.remove method执行此操作:

from xml.etree import ElementTree

root = ElementTree.fromstring(your_xml_string)    
for elem in root.findall("cpu"):
    root.remove(elem)

答案 1 :(得分:0)

这将删除带有标记&#34; cpu&#34;

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

如果你想删除所有提及&#34; cpu&#34;在标记中,您应该使用if elem.tag in "cpu"