# HG changeset patch # User Goffi # Date 1666975637 -7200 # Node ID 323017a4e4d24d32f03895a8bb14467ded1e290c # Parent 1ab16449577b5e57cd92277583d9b1023ab800d8 tools (xml_tools): `domish_elt_2_et_elt` and `et_elt_2_domish_elt` now handle lxml.etree diff -r 1ab16449577b -r 323017a4e4d2 sat/tools/xml_tools.py --- a/sat/tools/xml_tools.py Fri Oct 28 18:47:17 2022 +0200 +++ b/sat/tools/xml_tools.py Fri Oct 28 18:47:17 2022 +0200 @@ -17,20 +17,23 @@ # along with this program. If not, see . -import re -from typing import Optional, Tuple +from collections import OrderedDict import html.entities -from collections import OrderedDict -from xml.dom import minidom, NotFoundErr -from twisted.words.xish import domish +import re +from typing import Optional, Tuple, Union, Literal, overload +from xml.dom import NotFoundErr, minidom +import xml.etree.ElementTree as ET +from lxml import etree + +from twisted.internet import defer from twisted.words.protocols.jabber import jid -from twisted.internet import defer +from twisted.words.xish import domish from wokkel import data_form + from sat.core import exceptions +from sat.core.constants import Const as C from sat.core.i18n import _ -from sat.core.constants import Const as C from sat.core.log import getLogger -import xml.etree.ElementTree as ET log = getLogger(__name__) @@ -1980,7 +1983,7 @@ return name[1:end_idx], name[end_idx+1:] -def et_elt_2_domish_elt(et_elt: ET.Element) -> domish.Element: +def et_elt_2_domish_elt(et_elt: Union[ET.Element, etree.Element]) -> domish.Element: """Convert ElementTree element to Twisted's domish.Element Note: this is a naive implementation, adapted to XMPP, and some content are ignored @@ -1995,18 +1998,35 @@ return elt -def domish_elt_2_et_elt(elt: domish.Element) -> ET.Element: +@overload +def domish_elt_2_et_elt(elt: domish.Element, lxml: Literal[False]) -> ET.Element: + ... + +@overload +def domish_elt_2_et_elt(elt: domish.Element, lxml: Literal[True]) -> etree.Element: + ... + +@overload +def domish_elt_2_et_elt( + elt: domish.Element, lxml: bool +) -> Union[ET.Element, etree.Element]: + ... + +def domish_elt_2_et_elt(elt, lxml = False): """Convert Twisted's domish.Element to ElementTree equivalent - Note: this is a naive implementation, adapter to XMPP, and some text content may be + Note: this is a naive implementation, adapted to XMPP, and some text content may be missing (content put after a tag, i.e. what would go to the "tail" attribute of ET Element) """ tag = f"{{{elt.uri}}}{elt.name}" if elt.uri else elt.name - et_elt = ET.Element(tag, attrib=elt.attributes) + if lxml: + et_elt = etree.Element(tag, attr=elt.attributes) + else: + et_elt = ET.Element(tag, attrib=elt.attributes) content = str(elt) if content: et_elt.text = str(elt) for child in elt.elements(): - et_elt.append(domish_elt_2_et_elt(child)) + et_elt.append(domish_elt_2_et_elt(child, lxml=lxml)) return et_elt