Code source de pyspc.io.xml.from_xml

#!/usr/bin/python3
# -*- coding: utf-8 -*-
########################################################################
#
# This file is part of python module <pyspc>.
# Copyright (C) 2013-2021  R. Marty
#   (renaud.marty@developpement-durable.gouv.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (see COPYING.txt).
# If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
"""
Bibliothèque pyspc du projet pyspc - IO - XML - Lecture de fichiers
Source : libhydro
"""


[docs] def from_file(filename): """Parse le fichier filename et retourne un ElementTree Parameters ---------- filename : str Nom de fichier XML Returns ------- tree : lxml.etree._ElementTree instance ElementTree renvoyée par lxml.etree.parse(filename) """ from lxml import etree as _etree # Création du lecteur du fichier # removes empty text between tags # discard comments # clean up redundant namespace declarations parser = _etree.XMLParser( remove_blank_text=True, remove_comments=True, ns_clean=True) # Application du lecteur sur le fichier tree = _etree.parse(filename, parser=parser) # nosec return tree
[docs] def get_attrib(element, attrib, cast=str): """Return cast(element/tag.text) or None.""" if element is not None: e = element.attrib[attrib] if e is not None: return apply_cast(text=e, cast=cast) return None
[docs] def get_value(element, tag, cast=str): """Return cast(element/tag.text) or None.""" if element is not None: e = element.find(tag) if (e is not None) and (e.text is not None): return apply_cast(text=e.text, cast=cast) return None
[docs] def apply_cast(text, cast=str): """Return cast(text)""" if cast == bool: # return wether text is a kind of True... or not return (str(text).lower() in ('true', 'vrai', '1', 'y', 'yes', 'oui')) # else return cast(text)
[docs] def remove_namespace(element, namespace): """Remove namespace in the passed etree.Element in place.""" ns = '{%s}' % namespace nsl = len(ns) for e in element.getiterator(): if e.tag.startswith(ns): e.tag = e.tag[nsl:]