diff sat/tools/xml_tools.py @ 3396:a4774f5b6b17

tools (xml_tools): `domish.Element` pretty formatting functions: - `pFmtElt`: pretty format a `domish.Element` - `ppElt`: use the above function to pretty print a `domish.Element`
author Goffi <goffi@goffi.org>
date Thu, 12 Nov 2020 14:53:15 +0100
parents d6a482a78bda
children 987198910e56
line wrap: on
line diff
--- a/sat/tools/xml_tools.py	Thu Nov 12 14:53:15 2020 +0100
+++ b/sat/tools/xml_tools.py	Thu Nov 12 14:53:15 2020 +0100
@@ -1812,3 +1812,27 @@
             yield child
         for found in findAll(child, namespaces, names):
             yield found
+
+
+def pFmtElt(elt, indent=0):
+    """Pretty format a domish.Element"""
+    strings = []
+    for child in elt.children:
+        if domish.IElement.providedBy(child):
+            strings.append(pFmtElt(child, indent+2))
+        else:
+            strings.append(f"{(indent+2)*' '}{child!s}")
+    if elt.children:
+        nochild_elt = domish.Element(
+            (elt.uri, elt.name), elt.defaultUri, elt.attribs, elt.localPrefixes
+        )
+        strings.insert(0, f"{indent*' '}{nochild_elt.toXml()[:-2]}>")
+        strings.append(f"{indent*' '}</{nochild_elt.name}>")
+    else:
+        strings.append(f"{indent*' '}{elt.toXml()}")
+    return '\n'.join(strings)
+
+
+def ppElt(elt):
+    """Pretty print a domish.Element"""
+    print(pFmtElt(elt))