需要帮助来修改xml与python

时间:2016-06-28 13:47:25

标签: python xml

我有一个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'。我怎么能这样做?

3 个答案:

答案 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)