2016-06-28 79 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')