2016-12-12 7 views
0

こんにちは、どうすればPythonのElementTree.fromstringを使って要素を削除できますか?ElementTree.fromstringを使用して要素を削除する方法

"cpu block"全体を削除したいのですが、助けてください。

あなたはとてもよう Element.remove methodでそれを行うことができます
<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> 

答えて

1

from xml.etree import ElementTree 

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

あなたがいずれかと言及を持つすべての要素を削除したい場合は、「CPU」

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

をタグを持つすべての要素を削除しますあなたが使うべきタグの "cpu" if elem.tag in "cpu"

関連する問題