2016-06-28 7 views
0

私は特定のインターフェースのモデルタイプを変更したいXML文字列を持っています。xmlをPythonで修正するのに助けが必要

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

は今、私はソースnetwork='nat'モデルtype='e1000'を変更したいです。どうやってやるの?

+2

:// docs.python.org/3 /ライブラリ/ xml.etree.elementtree.html' –

+0

[lxmlの]あなたは1回の呼び出しでそれを行うことができます(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

あなたの答えのおかげで、これも私のためにあなたが複数のfind*()呼び出しを必要としない

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

を働いています。

あなたが `httpsをここで必要eveythin見つけることができますかなり確信して
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') 
関連する問題