blob: 84b56c28f19d426b2a50ff1e4027c94243f92bc8 [file] [log] [blame]
Dan Smithba6cb162012-08-14 07:22:42 -07001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2#
Kurt Taylor6a6f5be2013-04-02 18:53:47 -04003# Copyright 2012 IBM Corp.
Dan Smithba6cb162012-08-14 07:22:42 -07004# All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License. You may obtain
8# a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15# License for the specific language governing permissions and limitations
16# under the License.
17
Attila Fazekasc74aede2013-09-11 13:04:02 +020018import collections
19
Dan Smithba6cb162012-08-14 07:22:42 -070020XMLNS_11 = "http://docs.openstack.org/compute/api/v1.1"
21
22
23# NOTE(danms): This is just a silly implementation to help make generating
24# XML faster for prototyping. Could be replaced with proper etree gorp
25# if desired
26class Element(object):
27 def __init__(self, element_name, *args, **kwargs):
28 self.element_name = element_name
29 self._attrs = kwargs
30 self._elements = list(args)
31
32 def add_attr(self, name, value):
33 self._attrs[name] = value
34
35 def append(self, element):
36 self._elements.append(element)
37
38 def __str__(self):
39 args = " ".join(['%s="%s"' % (k, v) for k, v in self._attrs.items()])
40 string = '<%s %s' % (self.element_name, args)
41 if not self._elements:
42 string += '/>'
43 return string
44
45 string += '>'
46
47 for element in self._elements:
48 string += str(element)
49
50 string += '</%s>' % self.element_name
51
52 return string
53
54 def __getitem__(self, name):
55 for element in self._elements:
56 if element.element_name == name:
57 return element
58 raise KeyError("No such element `%s'" % name)
59
60 def __getattr__(self, name):
61 if name in self._attrs:
62 return self._attrs[name]
63 return object.__getattr__(self, name)
64
65 def attributes(self):
66 return self._attrs.items()
67
68 def children(self):
69 return self._elements
70
71
72class Document(Element):
73 def __init__(self, *args, **kwargs):
74 if 'version' not in kwargs:
75 kwargs['version'] = '1.0'
76 if 'encoding' not in kwargs:
77 kwargs['encoding'] = 'UTF-8'
78 Element.__init__(self, '?xml', *args, **kwargs)
79
80 def __str__(self):
81 args = " ".join(['%s="%s"' % (k, v) for k, v in self._attrs.items()])
82 string = '<?xml %s?>\n' % args
83 for element in self._elements:
84 string += str(element)
85 return string
86
87
88class Text(Element):
89 def __init__(self, content=""):
90 Element.__init__(self, None)
91 self.__content = content
92
93 def __str__(self):
94 return self.__content
95
96
97def xml_to_json(node):
98 """This does a really braindead conversion of an XML tree to
99 something that looks like a json dump. In cases where the XML
100 and json structures are the same, then this "just works". In
Attila Fazekasb2902af2013-02-16 16:22:44 +0100101 others, it requires a little hand-editing of the result.
102 """
Dan Smithba6cb162012-08-14 07:22:42 -0700103 json = {}
104 for attr in node.keys():
Davanum Srinivas8d226cc2013-03-08 09:35:36 -0500105 if not attr.startswith("xmlns"):
106 json[attr] = node.get(attr)
Dan Smithba6cb162012-08-14 07:22:42 -0700107 if not node.getchildren():
108 return node.text or json
109 for child in node.getchildren():
110 tag = child.tag
111 if tag.startswith("{"):
112 ns, tag = tag.split("}", 1)
113 json[tag] = xml_to_json(child)
114 return json
Attila Fazekasc74aede2013-09-11 13:04:02 +0200115
116
117def deep_dict_to_xml(dest, source):
118 """Populates the ``dest`` xml element with the ``source`` ``Mapping``
119 elements, if the source Mapping's value is also a ``Mapping``
120 they will be recursively added as a child elements.
121 :param source: A python ``Mapping`` (dict)
122 :param dest: XML child element will be added to the ``dest``
123 """
124 for element, content in source.iteritems():
125 if isinstance(content, collections.Mapping):
126 xml_element = Element(element)
127 deep_dict_to_xml(xml_element, content)
128 dest.append(xml_element)
129 else:
130 dest.append(Element(element, content))