blob: 0746f3a5d31c700afe71dee7dacf1f7762c62641 [file] [log] [blame]
adminbae64d82013-08-01 10:50:15 -07001'''
2Created on 03-Dec-2012
Jeremy Songsterae01bba2016-07-11 15:39:17 -07003Modified 2015 by ON.Lab
4
5Please refer questions to either the onos test mailing list at <onos-test@onosproject.org>,
6the System Testing Plans and Results wiki page at <https://wiki.onosproject.org/x/voMg>,
7or the System Testing Guide page at <https://wiki.onosproject.org/x/WYQg>
adminbae64d82013-08-01 10:50:15 -07008
9@author: Anil Kumar (anilkumar.s@paxterrasolutions.com)
10
11 TestON is free software: you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation, either version 2 of the License, or
14 (at your option) any later version.
15
16 TestON is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
20
21 You should have received a copy of the GNU General Public License
Jon Hall4ba53f02015-07-29 13:07:41 -070022 along with TestON. If not, see <http://www.gnu.org/licenses/>.
adminbae64d82013-08-01 10:50:15 -070023
24'''
25
26"""
27 xmldict
28 ~~~~~~~~~~~~~~~~~~~~~~~~~
29
30 Convert xml to python dictionaries.
31"""
32import datetime
33
34def xml_to_dict(root_or_str, strict=True):
35 """
36 Converts `root_or_str` which can be parsed xml or a xml string to dict.
37
38 """
39 root = root_or_str
40 if isinstance(root, str):
41 import xml.etree.cElementTree as ElementTree
42 root = ElementTree.XML(root_or_str)
43 try :
44 return {root.tag: _from_xml(root, strict)}
Jon Hall1306a562015-09-04 11:21:24 -070045 except StandardError:
adminbae64d82013-08-01 10:50:15 -070046 return None
47
48def dict_to_xml(dict_xml):
49 """
50 Converts `dict_xml` which is a python dict to corresponding xml.
51 """
52 return _to_xml(dict_xml)
53
54def _to_xml(el):
55 """
56 Converts `el` to its xml representation.
57 """
58 val = None
59 if isinstance(el, dict):
60 val = _dict_to_xml(el)
61 elif isinstance(el, bool):
62 val = str(el).lower()
63 else:
64 val = el
65 if val is None: val = 'null'
66 return val
67
68def _extract_attrs(els):
69 """
70 Extracts attributes from dictionary `els`. Attributes are keys which start
71 with '@'
72 """
73 if not isinstance(els, dict):
74 return ''
75 return ''.join(' %s="%s"' % (key[1:], value) for key, value in els.iteritems()
76 if key.startswith('@'))
77
78def _dict_to_xml(els):
79 """
80 Converts `els` which is a python dict to corresponding xml.
81 """
82 def process_content(tag, content):
83 attrs = _extract_attrs(content)
84 text = isinstance(content, dict) and content.get('#text', '') or ''
85 return '<%s%s>%s%s</%s>' % (tag, attrs, _to_xml(content), text, tag)
86
87 tags = []
88 for tag, content in els.iteritems():
89 # Text and attributes
90 if tag.startswith('@') or tag == '#text':
91 continue
92 elif isinstance(content, list):
93 for el in content:
94 tags.append(process_content(tag, el))
95 elif isinstance(content, dict):
96 tags.append(process_content(tag, content))
97 else:
98 tags.append('<%s>%s</%s>' % (tag, _to_xml(content), tag))
99 return ''.join(tags)
100
101def _is_xml_el_dict(el):
102 """
103 Returns true if `el` is supposed to be a dict.
104 This function makes sense only in the context of making dicts out of xml.
105 """
106 if len(el) == 1 or el[0].tag != el[1].tag:
107 return True
108 return False
109
110def _is_xml_el_list(el):
111 """
112 Returns true if `el` is supposed to be a list.
113 This function makes sense only in the context of making lists out of xml.
114 """
115 if len(el) > 1 and el[0].tag == el[1].tag:
116 return True
117 return False
118
119def _str_to_datetime(date_str):
120 try:
121 val = datetime.datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%SZ")
122 except ValueError:
123 val = date_str
124 return val
125
126def _str_to_boolean(bool_str):
127 if bool_str.lower() != 'false' and bool(bool_str):
128 return True
129 return False
130
131def _from_xml(el, strict):
132 """
133 Extracts value of xml element element `el`.
134 """
135 val = None
136 # Parent node.
137 if el:
138 if _is_xml_el_dict(el):
139 val = _dict_from_xml(el, strict)
140 elif _is_xml_el_list(el):
141 val = _list_from_xml(el, strict)
142 # Simple node.
143 else:
144 attribs = el.items()
145 # An element with attributes.
146 if attribs and strict:
147 val = dict(('@%s' % k, v) for k, v in dict(attribs).iteritems())
148 if el.text:
149 converted = _val_and_maybe_convert(el)
150 val['#text'] = el.text
151 if converted != el.text:
152 val['#value'] = converted
153 elif el.text:
154 # An element with no subelements but text.
155 val = _val_and_maybe_convert(el)
156 elif attribs:
157 val = dict(attribs)
158 return val
159
160def _val_and_maybe_convert(el):
161 """
162 Converts `el.text` if `el` has attribute `type` with valid value.
163 """
164 text = el.text.strip()
165 data_type = el.get('type')
166 convertor = _val_and_maybe_convert.convertors.get(data_type)
167 if convertor:
168 return convertor(text)
169 else:
170 return text
171_val_and_maybe_convert.convertors = {
172 'boolean': _str_to_boolean,
173 'datetime': _str_to_datetime,
174 'integer': int
175}
176
177def _list_from_xml(els, strict):
178 """
179 Converts xml elements list `el_list` to a python list.
180 """
181
182 temp = {}
183 for el in els:
184 tag = el.attrib["name"]
185 temp[tag] = (_from_xml(el, strict))
186 return temp
187
188def _dict_from_xml(els, strict):
189 """
190 Converts xml doc with root `root` to a python dict.
191 """
192 # An element with subelements.
193 res = {}
194 for el in els:
195 res[el.tag] = _from_xml(el, strict)
196 return res