changeset 3491:2bd75fc2555d

tools (xml_tools): new findAncestor method: this methods help to find a `domish.Element` ancestor with specific name/namespace
author Goffi <goffi@goffi.org>
date Sat, 27 Mar 2021 14:35:07 +0100
parents 509f7a1c67dc
children fa796612adad
files sat/tools/xml_tools.py
diffstat 1 files changed, 25 insertions(+), 11 deletions(-) [+]
line wrap: on
line diff
--- 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 <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.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 = []