# -*- coding: utf-8 -*- # # Copyright 2019-2020 Fabien Bourgeois # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """ XML helpers and macros """ from os import path import xml.etree.ElementTree as ET from xml.dom import minidom def xmlroot(tree): """ Special process for root XML Node """ rootel = ET.Element(tree['tag'], tree['attrs']) children = tree['children'] if children: xmlchild(rootel, children) return rootel def xmlchild(parent, children): """ Handling of children (ie non root) XML Nodes with/o text and subchildren (recursive) """ for child in children: if isinstance(child, str): parent.text = child else: attrs = {unicode(k): unicode(v) for [k, v] in child['attrs'].items()} new_parent = ET.SubElement(parent, child['tag'], attrs) subchildren = child['children'] if subchildren: xmlchild(new_parent, subchildren) def xmln(tag='', attrs=None, children=None, text=False): """ XMLNode with default children, not attributes """ children = ([text] if text else children) or [] return {'tag': tag, 'attrs': attrs or {}, 'children': children} def xml_write(filepath, tree): """ Write XML file according to filename and given tree """ output_xml = minidom.parseString(ET.tostring(tree)).toprettyxml(indent=' ') output_path = path.dirname(path.abspath(filepath)) fpath = '%s/%s' % (output_path, path.basename(filepath).replace('.py', '_views.xml')) with open(fpath, 'w') as output_file: output_file.write(output_xml)