• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# coding=utf-8
3
4# Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import os
18from xml.etree import cElementTree as ElementTree
19
20class XmlParser:
21    def __init__(self):
22        self.d2xml_level = 0
23        self.indent = '  '
24
25    def _dict_to_xml(self, data, root='object'):
26        if isinstance(data, dict):
27            xml_ret = '  ' * self.d2xml_level + f'<{root}>\n'
28            self.d2xml_level += 1
29            for key, value in data.items():
30                xml_ret += self._dict_to_xml(value, key)
31            self.d2xml_level -= 1
32            xml_ret += '  ' * self.d2xml_level + f'</{root}>\n'
33            return xml_ret
34
35        if isinstance(data, (list, tuple, set)):
36            xml_ret = ''
37            for item in data:
38                xml_ret += self._dict_to_xml(item, root)
39            return xml_ret
40        if data is None:
41            data = ''
42        xml_ret = '  ' * self.d2xml_level + f'<{root}>'
43        xml_ret += str(data)
44        xml_ret += f'</{root}>\n'
45        return xml_ret
46
47    def dict_to_xml(self, data, root='object'):
48        self.d2xml_level = 0
49        xml_str = '<?xml version="1.0" encoding="UTF-8"?>\n'
50        xml_str += self._dict_to_xml(data, root)
51        return xml_str
52
53    def et2dict(self, root):
54        xml_dict = {}
55        if root.items():
56            xml_dict.update(dict(root.items()))
57        for element in root:
58            if element:
59                key = element.tag
60                val = self.et2dict(element)
61            else:
62                key = element.tag
63                val = element.text
64
65            if key not in xml_dict:
66                xml_dict[key] = val
67                continue
68
69            if not isinstance(xml_dict[key], list):
70                xml_dict[key] = [xml_dict[key]]
71            temp = xml_dict[key]
72            temp.append(val)
73            xml_dict[key] = temp
74        return xml_dict
75
76    def xml2dict(self, xml_file):
77        tree = ElementTree.parse(xml_file)
78        root = tree.getroot()
79        return self.et2dict(root)
80
81if __name__ == "__main__":
82    script_dir = os.path.split(os.path.realpath(__file__))[0]
83    file = os.path.join(script_dir, 'sdk_template', 'template.ewp')
84    test = XmlParser()
85    dict_ = test.xml2dict(file)
86    xml = test.dict_to_xml(dict_, root='project')
87    print(xml)
88