如何使用python将新数据附加到现有xml

时间:2016-06-24 11:24:54

标签: python xml

Hello这是我现有的xml文件

<domain type='kvm'>
      <name>mydomain</name>
      <features>
        <acpi/>
        <apic/>
        <pae/>
      </features>
      <devices>
        <disk type='block' device='disk'>
          <driver name='qemu' type='raw' cache='none'/>
          <source dev='/dev/mydomain'/>
          <target dev='vda' bus='virtio'/>
        </disk>
      </devices>
</domain>

我想在“设备”部分的上面的xml中附加另一个“磁盘部分”,这样我的新xml会喜欢这个。

<domain type='kvm'>
      <name>mydomain</name>
      <features>
        <acpi/>
        <apic/>
        <pae/>
      </features>
      <devices>
        <disk type='block' device='disk'>
          <driver name='qemu' type='raw' cache='none'/>
          <source dev='/dev/mydomain'/>
          <target dev='vda' bus='virtio'/>
        </disk>
        <disk type='block' device='disk'>
          <driver name='qemu' type='raw' cache='none'/>
          <source dev='/dev/mydomain2'/>
          <target dev='vdb' bus='virtio'/>
        </disk>
      </devices>
</domain>

请问我如何使用Python XML

欧麦尔

1 个答案:

答案 0 :(得分:0)

您可以使用ElementTree来解析和更新XML。

这是一个代码。

import xml.etree.ElementTree as ET

def get_new_element():
    #create element and set attributes
    disk = ET.Element('disk')
    disk.attrib['type'] = 'block'
    disk.attrib['device'] = 'disk'

    #create sub-element and set attributes
    driver = ET.SubElement(disk, 'driver')
    driver.attrib['name'] = 'qemu'
    driver.attrib['type'] = 'raw'
    driver.attrib['cache'] = 'none'

    source = ET.SubElement(disk, 'source')
    source.attrib['dev'] = '/dev/mydomain2'

    target = ET.SubElement(disk, 'target')
    target.attrib['dev'] = 'vdb'
    target.attrib['bus'] = 'virtio'

    return disk


if __name__ == '__main__':
    xml_tree = ET.parse('data.xml')
    devices_element = xml_tree.find('devices')

    new_element = get_new_element()
    devices_element.append(new_element)

    new_xml_tree_string = ET.tostring(xml_tree.getroot())

    with open('updated_data.xml', "wb") as f:
        f.write(new_xml_tree_string)

对于pretty XML,请关注:Pretty-Printing XML