(write: Callable[[str], None], elem: Element, format: Literal["html", "xhtml"])
| 138 | |
| 139 | |
| 140 | def _serialize_html(write: Callable[[str], None], elem: Element, format: Literal["html", "xhtml"]) -> None: |
| 141 | stack: deque[Element | str] = deque([elem]) |
| 142 | |
| 143 | count = 0 |
| 144 | while stack: |
| 145 | count += 1 |
| 146 | el = stack.popleft() |
| 147 | |
| 148 | if isinstance(el, str): |
| 149 | write(el) |
| 150 | continue |
| 151 | |
| 152 | tag = el.tag |
| 153 | text = el.text |
| 154 | |
| 155 | if tag is Comment: |
| 156 | write(f"<!--{_escape_cdata(text)}-->") |
| 157 | elif tag is ProcessingInstruction: |
| 158 | write(f"<?{_escape_cdata(text)}?>") |
| 159 | elif tag is None: |
| 160 | if text: |
| 161 | write(_escape_cdata(text)) |
| 162 | # Add the children in reverse order so we process them in the right order. |
| 163 | if el.tail: |
| 164 | stack.appendleft(_escape_cdata(el.tail)) |
| 165 | stack.extendleft(reversed(el)) |
| 166 | continue |
| 167 | else: |
| 168 | namespace_uri = None |
| 169 | if isinstance(tag, QName): |
| 170 | # `QNAME` objects store their data as a string: `{uri}tag` |
| 171 | if tag.text[:1] == "{": |
| 172 | namespace_uri, tag = tag.text[1:].split("}", 1) |
| 173 | else: |
| 174 | raise ValueError('QName objects must define a tag.') |
| 175 | write(f"<{tag}") |
| 176 | items = el.items() |
| 177 | if items: |
| 178 | items = sorted(items) # lexical order |
| 179 | for k, v in items: |
| 180 | if isinstance(k, QName): |
| 181 | # Assume a text only `QName` |
| 182 | k = k.text |
| 183 | if isinstance(v, QName): |
| 184 | # Assume a text only `QName` |
| 185 | v = v.text |
| 186 | if v is None: |
| 187 | # A valueless attribute is preserved exactly as it |
| 188 | # was provided: render the bare attribute name. |
| 189 | write(f" {k}") |
| 190 | else: |
| 191 | v = _escape_attrib_html(v) |
| 192 | if k == v and format == 'html' and k in BOOLEAN_ATTRIBUTES['html']: |
| 193 | # handle boolean attributes |
| 194 | write(f" {v}") |
| 195 | else: |
| 196 | write(f' {k}="{v}"') |
| 197 | if namespace_uri: |
no test coverage detected