如何使用python将新数据附加到现有xml中
你好,这是我现有的xml文件如何使用python将新数据附加到现有xml中,python,xml,Python,Xml,你好,这是我现有的xml文件 <domain type='kvm'> <name>mydomain</name> <features> <acpi/> <apic/> <pae/> </features> <devices> <disk type='block' devic
<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>
mydomain
我想将另一个“磁盘部分”附加到上述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>
mydomain
您能帮助我如何使用Python XML吗
比尔
Umar可以用来解析和更新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如下:Hello parshkr,感谢您的帮助,我将XML作为文件保存在变量中,因此我需要在ET.parse()的替代方案中使用什么?您可以使用ET.fromstring(您的XML字符串)
。在这种情况下,我相信你不需要做xml\u tree.getroot()
@眼泪不需要感谢我,只要投票并接受答案即可