我有一个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'
的模型network='nat'
。我怎么能这样做?
答案 0 :(得分: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')
答案 1 :(得分: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
。
答案 2 :(得分: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)