yaltik_odoo_custom/xml_dsl/base.py

47 lines
1.8 KiB
Python

# -*- coding: utf-8 -*-
#
# Copyright 2019 Fabien Bourgeois <fabien@yaltik.com>
#
# 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 <http://www.gnu.org/licenses/>.
""" XML helpers and macros """
from xml.etree import ElementTree as ET
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}