tools(xml_tools): fixed <div> unwrapping + added parse instance:

`<div>` unwrapping could fail when a text node was a sibling of the top element (could
easily happen ith a `\n` line feed added by an editor). This is fixed by filtering on
IElement with `elements()`.

A `parse` instance has been added as it is not necessary to create a new `ElementParser`
each time that we want to parse something.
This commit is contained in:
Goffi 2020-11-12 14:53:15 +01:00
commit 1167c12c6f

View file

@ -1701,8 +1701,8 @@ def isXHTMLField(field):
field.value.uri == C.NS_XHTML)
class ElementParser(object):
"""callable class to parse XML string into Element"""
class ElementParser:
"""Callable class to parse XML string into Element"""
# XXX: Found at http://stackoverflow.com/questions/2093400/how-to-create-twisted-words-xish-domish-element-entirely-from-raw-xml/2095942#2095942
@ -1758,12 +1758,16 @@ class ElementParser(object):
parser.parse(tmp.toXml().encode("utf-8"))
top_elt = self.result.firstChildElement()
# we now can check if there was a unique element on the top
# and remove our wrapping <div/> is this was the case
if len(top_elt.children) == 1 and domish.IElement.providedBy(top_elt.children[0]):
top_elt = top_elt.firstChildElement()
# and remove our wrapping <div/> is this is the case
top_elt_children = list(top_elt.elements())
if len(top_elt_children) == 1:
top_elt = top_elt_children[0]
return top_elt
parse = ElementParser()
# FIXME: this method is duplicated from frontends.tools.xmlui.getText
def getText(node):
"""Get child text nodes of a domish.Element.