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.
master
Dustin 2015-08-06 15:49:50 -05:00
parent 167cc3b198
commit 9549fd984b
1 changed files with 16 additions and 7 deletions

View File

@ -1,10 +1,16 @@
from . import storage from . import storage
from xml.etree import ElementTree as etree
import logging import logging
import os import os
import re import re
import tempfile import tempfile
import yaml 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__) log = logging.getLogger(__name__)
@ -272,7 +278,7 @@ class VirtualMachine(object):
storage.deactivate_vg(self.vg_name) storage.deactivate_vg(self.vg_name)
self._disk.deactivate() self._disk.deactivate()
def to_xml(self): def to_xml(self, pretty_print=False):
root = etree.Element('domain', type='kvm') root = etree.Element('domain', type='kvm')
etree.SubElement(root, 'name').text = self.name etree.SubElement(root, 'name').text = self.name
@ -357,22 +363,25 @@ class VirtualMachine(object):
if self.video == 'qxl': if self.video == 'qxl':
elm_video = etree.SubElement(elm_devices, 'video') elm_video = etree.SubElement(elm_devices, 'video')
elm_model = etree.SubElement(elm_video, 'model') elm_model = etree.SubElement(elm_video, 'model')
elm_model.attrib.update( elm_model.attrib.update(dict(
type=self.video, type=self.video,
ram='65536', ram='65536',
vram='65536', vram='65536',
heads='1', heads='1',
) ))
elif self.video: elif self.video:
elm_video = etree.SubElement(elm_devices, 'video') elm_video = etree.SubElement(elm_devices, 'video')
elm_model = etree.SubElement(elm_video, 'model') elm_model = etree.SubElement(elm_video, 'model')
elm_model.attrib.update( elm_model.attrib.update(dict(
type=self.video, type=self.video,
vram='9216', vram='9216',
heads='1', 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): def _partition_gpt(self):
storage.partition_gpt(self._disk.blockdev, self.partitions) storage.partition_gpt(self._disk.blockdev, self.partitions)