tools (xml_tools): new findAncestor method:

this methods help to find a `domish.Element` ancestor with specific name/namespace
This commit is contained in:
Goffi 2021-03-27 14:35:07 +01:00
commit 839aea4e2b

View file

@ -1,6 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# SAT: a jabber client # SAT: a jabber client
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org) # Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
@ -17,21 +16,23 @@
# You should have received a copy of the GNU Affero General Public License # 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/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
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.i18n import _
from sat.core.constants import Const as C from sat.core.constants import Const as C
from sat.core.log import getLogger from sat.core.log import getLogger
log = getLogger(__name__)
from xml.dom import minidom, NotFoundErr log = getLogger(__name__)
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)""" """This library help manage XML used in SàT (parameters, registration, etc)"""
@ -1904,6 +1905,19 @@ def findAll(elt, namespaces=None, names=None):
yield found 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=""): def pFmtElt(elt, indent=0, defaultUri=""):
"""Pretty format a domish.Element""" """Pretty format a domish.Element"""
strings = [] strings = []