From 9549fd984bb396e56473912d994f61beaff39555 Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Thu, 6 Aug 2015 15:49:50 -0500 Subject: [PATCH] VirtualMachine: to_xml(): Add pretty_print keyword If the `lxml` package is available, its ElementTree implementation is used instead of the one in the Python standard library. This implementation provides a "pretty print" option when serializing XML documents. Note that since `Element.attrib` is not a "real" dictionary object, it does not accept keyword arguments to its `update` method, so a dictionary must be passed in instead. This is used in a few places to set element attributes in bulk. --- src/mkvm/vmdesc.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/mkvm/vmdesc.py b/src/mkvm/vmdesc.py index 4fe69f5..86529d5 100644 --- a/src/mkvm/vmdesc.py +++ b/src/mkvm/vmdesc.py @@ -1,10 +1,16 @@ from . import storage -from xml.etree import ElementTree as etree import logging import os import re import tempfile import yaml +try: + import lxml +except ImportError: + lxml = None + from xml.etree import ElementTree as etree +else: + from lxml import etree log = logging.getLogger(__name__) @@ -272,7 +278,7 @@ class VirtualMachine(object): storage.deactivate_vg(self.vg_name) self._disk.deactivate() - def to_xml(self): + def to_xml(self, pretty_print=False): root = etree.Element('domain', type='kvm') etree.SubElement(root, 'name').text = self.name @@ -357,22 +363,25 @@ class VirtualMachine(object): if self.video == 'qxl': elm_video = etree.SubElement(elm_devices, 'video') elm_model = etree.SubElement(elm_video, 'model') - elm_model.attrib.update( + elm_model.attrib.update(dict( type=self.video, ram='65536', vram='65536', heads='1', - ) + )) elif self.video: elm_video = etree.SubElement(elm_devices, 'video') elm_model = etree.SubElement(elm_video, 'model') - elm_model.attrib.update( + elm_model.attrib.update(dict( type=self.video, vram='9216', heads='1', - ) + )) - return etree.tostring(root, encoding='unicode') + kwargs = {'encoding': 'unicode'} + if lxml: + kwargs['pretty_print'] = pretty_print + return etree.tostring(root, **kwargs) def _partition_gpt(self): storage.partition_gpt(self._disk.blockdev, self.partitions)