(write: Callable[[str], None], elem: Element, format: Literal["html", "xhtml"])
| 116 | |
| 117 | |
| 118 | def _serialize_html(write: Callable[[str], None], elem: Element, format: Literal["html", "xhtml"]) -> None: |
| 119 | tag = elem.tag |
| 120 | text = elem.text |
| 121 | if tag is Comment: |
| 122 | write("<!--%s-->" % _escape_cdata(text)) |
| 123 | elif tag is ProcessingInstruction: |
| 124 | write("<?%s?>" % _escape_cdata(text)) |
| 125 | elif tag is None: |
| 126 | if text: |
| 127 | write(_escape_cdata(text)) |
| 128 | for e in elem: |
| 129 | _serialize_html(write, e, format) |
| 130 | else: |
| 131 | namespace_uri = None |
| 132 | if isinstance(tag, QName): |
| 133 | # `QNAME` objects store their data as a string: `{uri}tag` |
| 134 | if tag.text[:1] == "{": |
| 135 | namespace_uri, tag = tag.text[1:].split("}", 1) |
| 136 | else: |
| 137 | raise ValueError('QName objects must define a tag.') |
| 138 | write("<" + tag) |
| 139 | items = elem.items() |
| 140 | if items: |
| 141 | items = sorted(items) # lexical order |
| 142 | for k, v in items: |
| 143 | if isinstance(k, QName): |
| 144 | # Assume a text only `QName` |
| 145 | k = k.text |
| 146 | if isinstance(v, QName): |
| 147 | # Assume a text only `QName` |
| 148 | v = v.text |
| 149 | else: |
| 150 | v = _escape_attrib_html(v) |
| 151 | if k == v and format == 'html': |
| 152 | # handle boolean attributes |
| 153 | write(" %s" % v) |
| 154 | else: |
| 155 | write(' {}="{}"'.format(k, v)) |
| 156 | if namespace_uri: |
| 157 | write(' xmlns="%s"' % (_escape_attrib(namespace_uri))) |
| 158 | if format == "xhtml" and tag.lower() in HTML_EMPTY: |
| 159 | write(" />") |
| 160 | else: |
| 161 | write(">") |
| 162 | if text: |
| 163 | if tag.lower() in ["script", "style"]: |
| 164 | write(text) |
| 165 | else: |
| 166 | write(_escape_cdata(text)) |
| 167 | for e in elem: |
| 168 | _serialize_html(write, e, format) |
| 169 | if tag.lower() not in HTML_EMPTY: |
| 170 | write("</" + tag + ">") |
| 171 | if elem.tail: |
| 172 | write(_escape_cdata(elem.tail)) |
| 173 | |
| 174 | |
| 175 | def _write_html(root: Element, format: Literal["html", "xhtml"] = "html") -> str: |
no test coverage detected
searching dependent graphs…