blob: 76ad1aa7b74ea9c29c3ea1c69890132e63dba5d9 [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"
ivan-zhu8f992be2013-07-31 14:56:58 +080021XMLNS_V3 = "http://docs.openstack.org/compute/api/v1.1"
Dan Smithba6cb162012-08-14 07:22:42 -070022
23
24# NOTE(danms): This is just a silly implementation to help make generating
25# XML faster for prototyping. Could be replaced with proper etree gorp
26# if desired
27class Element(object):
28 def __init__(self, element_name, *args, **kwargs):
29 self.element_name = element_name
30 self._attrs = kwargs
31 self._elements = list(args)
32
33 def add_attr(self, name, value):
34 self._attrs[name] = value
35
36 def append(self, element):
37 self._elements.append(element)
38
39 def __str__(self):
ivan-zhuae5f98a2013-10-18 15:57:54 +080040 args = " ".join(['%s="%s"' %
41 (k, v if v is not None else "")
42 for k, v in self._attrs.items()])
Dan Smithba6cb162012-08-14 07:22:42 -070043 string = '<%s %s' % (self.element_name, args)
44 if not self._elements:
45 string += '/>'
46 return string
47
48 string += '>'
49
50 for element in self._elements:
51 string += str(element)
52
53 string += '</%s>' % self.element_name
54
55 return string
56
57 def __getitem__(self, name):
58 for element in self._elements:
59 if element.element_name == name:
60 return element
61 raise KeyError("No such element `%s'" % name)
62
63 def __getattr__(self, name):
64 if name in self._attrs:
65 return self._attrs[name]
66 return object.__getattr__(self, name)
67
68 def attributes(self):
69 return self._attrs.items()
70
71 def children(self):
72 return self._elements
73
74
75class Document(Element):
76 def __init__(self, *args, **kwargs):
77 if 'version' not in kwargs:
78 kwargs['version'] = '1.0'
79 if 'encoding' not in kwargs:
80 kwargs['encoding'] = 'UTF-8'
81 Element.__init__(self, '?xml', *args, **kwargs)
82
83 def __str__(self):
ivan-zhuae5f98a2013-10-18 15:57:54 +080084 args = " ".join(['%s="%s"' %
85 (k, v if v is not None else "")
86 for k, v in self._attrs.items()])
Dan Smithba6cb162012-08-14 07:22:42 -070087 string = '<?xml %s?>\n' % args
88 for element in self._elements:
89 string += str(element)
90 return string
91
92
93class Text(Element):
94 def __init__(self, content=""):
95 Element.__init__(self, None)
96 self.__content = content
97
98 def __str__(self):
99 return self.__content
100
101
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100102def parse_array(node, plurals=None):
103 array = []
104 for child in node.getchildren():
105 array.append(xml_to_json(child,
106 plurals))
107 return array
108
109
110def xml_to_json(node, plurals=None):
Dan Smithba6cb162012-08-14 07:22:42 -0700111 """This does a really braindead conversion of an XML tree to
112 something that looks like a json dump. In cases where the XML
113 and json structures are the same, then this "just works". In
Attila Fazekasb2902af2013-02-16 16:22:44 +0100114 others, it requires a little hand-editing of the result.
115 """
Dan Smithba6cb162012-08-14 07:22:42 -0700116 json = {}
117 for attr in node.keys():
Davanum Srinivas8d226cc2013-03-08 09:35:36 -0500118 if not attr.startswith("xmlns"):
119 json[attr] = node.get(attr)
Dan Smithba6cb162012-08-14 07:22:42 -0700120 if not node.getchildren():
121 return node.text or json
122 for child in node.getchildren():
123 tag = child.tag
124 if tag.startswith("{"):
125 ns, tag = tag.split("}", 1)
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100126 if plurals is not None and tag in plurals:
Andrea Frittoli513c8392014-01-10 14:16:34 +0000127 json[tag] = parse_array(child, plurals)
Rossella Sblendidoc1724112013-11-28 14:16:48 +0100128 else:
Andrea Frittoli513c8392014-01-10 14:16:34 +0000129 json[tag] = xml_to_json(child, plurals)
Dan Smithba6cb162012-08-14 07:22:42 -0700130 return json
Attila Fazekasc74aede2013-09-11 13:04:02 +0200131
132
133def deep_dict_to_xml(dest, source):
134 """Populates the ``dest`` xml element with the ``source`` ``Mapping``
135 elements, if the source Mapping's value is also a ``Mapping``
136 they will be recursively added as a child elements.
137 :param source: A python ``Mapping`` (dict)
138 :param dest: XML child element will be added to the ``dest``
139 """
140 for element, content in source.iteritems():
141 if isinstance(content, collections.Mapping):
142 xml_element = Element(element)
143 deep_dict_to_xml(xml_element, content)
144 dest.append(xml_element)
145 else:
146 dest.append(Element(element, content))