# HG changeset patch # User Goffi # Date 1616852107 -3600 # Node ID 2bd75fc2555d83c3f8ab62d7080f481c73ef2879 # Parent 509f7a1c67dccf4387fe486728f4b05901d339c7 tools (xml_tools): new findAncestor method: this methods help to find a `domish.Element` ancestor with specific name/namespace diff -r 509f7a1c67dc -r 2bd75fc2555d sat/tools/xml_tools.py --- a/sat/tools/xml_tools.py Tue Mar 23 21:21:00 2021 +0100 +++ b/sat/tools/xml_tools.py Sat Mar 27 14:35:07 2021 +0100 @@ -1,6 +1,5 @@ #!/usr/bin/env python3 - # SAT: a jabber client # Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org) @@ -17,22 +16,24 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . + +import re +from typing import Optional +import html.entities +from collections import OrderedDict +from xml.dom import minidom, NotFoundErr +from twisted.words.xish import domish +from twisted.words.protocols.jabber import jid +from twisted.internet import defer +from wokkel import data_form +from sat.core import exceptions from sat.core.i18n import _ from sat.core.constants import Const as C from sat.core.log import getLogger + log = getLogger(__name__) -from xml.dom import minidom, NotFoundErr -from wokkel import data_form -from twisted.words.xish import domish -from twisted.words.protocols.jabber import jid -from twisted.internet import defer -from sat.core import exceptions -from collections import OrderedDict -import html.entities -import re - """This library help manage XML used in SàT (parameters, registration, etc)""" SAT_FORM_PREFIX = "SAT_FORM_" @@ -1904,6 +1905,19 @@ yield found +def findAncestor(elt, name: str, namespace: Optional[str] = None) -> domish.Element: + """Retrieve ancestor of an element""" + current = elt.parent + while True: + if current is None: + raise exceptions.NotFound( + f"Can't find any ancestor {name!r} (xmlns: {namespace!r})" + ) + if current.name == name and (namespace is None or current.uri == namespace): + return current + current = current.parent + + def pFmtElt(elt, indent=0, defaultUri=""): """Pretty format a domish.Element""" strings = []