2016-06-28 101 views
0

我有一個XML字符串,我想修改特定接口的模型類型。需要幫助來修改與python xml

<domain type='kvm'> 
    <devices> 
    <interface type='network'> 
     <mac address='52:54:00:a8:fe:3d'/> 
     <source network='ovirtmgmt'/> 
     <model type='virtio'/> 
    </interface> 
    <interface type='network'> 
     <mac address='52:54:00:a8:fe:7d'/> 
     <source network='nat'/> 
     <model type='virtio'/> 
    </interface> 
    <interface type='network'> 
     <mac address='52:80:00:a8:66:20'/> 
     <source network='vm'/> 
     <model type='virtio'/> 
    </interface> 
    </devices> 
</domain> 

現在,我要換模型type='e1000'其中source network='nat'。我怎樣才能做到這一點?

+2

敢肯定你能找到eveythin你所需要的'https://開頭docs.python.org/3 /庫/ xml.etree.elementtree.html' –

+0

[LXML] (http://lxml.de/)是另一個最愛。 – wwii

回答

0

下面是一些簡單的ElementTree代碼來完成這項工作。在一個真正的程序中,你可能需要一些錯誤檢查。但是如果你確定你的XML數據將永遠是完美的,並且每個interface標籤將始終包含一個source標籤和一個model標籤,那麼此代碼將完成這項工作。

import xml.etree.cElementTree as ET 

data = ''' 
<domain type='kvm'> 
    <devices> 
    <interface type='network'> 
     <mac address='52:54:00:a8:fe:3d'/> 
     <source network='ovirtmgmt'/> 
     <model type='virtio'/> 
    </interface> 
    <interface type='network'> 
     <mac address='52:54:00:a8:fe:7d'/> 
     <source network='nat'/> 
     <model type='virtio'/> 
    </interface> 
    <interface type='network'> 
     <mac address='52:80:00:a8:66:20'/> 
     <source network='vm'/> 
     <model type='virtio'/> 
    </interface> 
    </devices> 
</domain> 
''' 

tree = ET.fromstring(data) 

for iface in tree.iterfind('devices/interface'): 
    network = iface.find('source').attrib['network'] 
    if network == 'nat': 
     model = iface.find('model') 
     model.attrib['type'] = 'e1000' 

ET.dump(tree) 

輸出

<domain type="kvm"> 
    <devices> 
    <interface type="network"> 
     <mac address="52:54:00:a8:fe:3d" /> 
     <source network="ovirtmgmt" /> 
     <model type="virtio" /> 
    </interface> 
    <interface type="network"> 
     <mac address="52:54:00:a8:fe:7d" /> 
     <source network="nat" /> 
     <model type="e1000" /> 
    </interface> 
    <interface type="network"> 
     <mac address="52:80:00:a8:66:20" /> 
     <source network="vm" /> 
     <model type="virtio" /> 
    </interface> 
    </devices> 
</domain> 

如果您使用的是舊版本的Python,你可能沒有iterfind。在這種情況下,請將其替換爲findall

0

謝謝您的回答,不過這也爲我工作

root = ET.fromstring(xml) 
for interface in root.findall('devices/interface'): 
    if interface.find('source/[@network="nat"]') != None: 
     model = interface.find('model') 
     model.set('type', 'e1000') 

new_xml = ET.tostring(root) 
1

你不需要多find*()電話。你能做到在一個電話:

from xml.etree import ElementTree as ET 

tree = ET.parse('input.xml') 

for model in tree.findall(".//source[@network='nat']/../model"): 
    model.set('type', 'e1000') 

tree.write('output.xml')