HTML Support¶
pygixml reads real-world (messy) HTML by first normalising it to well-formed XML, then handing that to the normal pugixml parser, and it can write a tree back out as HTML. All of it runs in C++, and every call crosses the Python/C++ boundary exactly once: the text goes in, the result comes out, and nothing is walked or built node by node from Python. Because the intermediate form is plain XML text, everything else in pygixml (XPath, objectify, dictify, jsonify) works on HTML with no extra code.
import pygixml
# 1. Parse straight to a DOM, then use XPath as usual
doc = pygixml.parse_html("<ul><li>a<li>b<br></ul>")
root = doc.first_child()
print([n.node.child_value() for n in root.select_nodes("//li")])
# 2. Or just get the XML text and feed it to anything
pygixml.html_to_xml("<ul><li>a<li>b<br></ul>")
# '<ul><li>a</li><li>b<br/></li></ul>'
# 3. Combine with dictify / jsonify
from pygixml import dictify
dictify.parse(pygixml.html_to_xml(page))
# 4. ...and back: edit the tree, write HTML
for n in doc.root.select_nodes("//script"):
n.node.parent.remove_child(n.node)
print(doc.to_html(pretty=True, unwrap="root"))
From the shell, HTML is both an input and an output format of
pygixml convert:
pygixml convert page.html --to json
pygixml convert messy.html -o clean.html -p # normalise + re-indent
pygixml convert data.xml --to html
Converting HTML to JSON/YAML/TOON goes through a dict, which keeps one value per
tag name: the text of an element is kept whole (<p>Hi<br>x</p> gives
{'p': {'br': None, '#text': 'Hix'}}, FormatDocument.from_html passes
cdata_separator="" to pygixml.dictify.parse()), but the order of text
and tags is not. Use --to html or --to xml when the order matters.
What gets fixed¶
void tags (
<br>,<img>, …) are self-closedimplicitly closed
<p>,<li>,<dt>/<dd>,<tr>,<td>/<th>,<tbody>,<option>, … (nested lists and tables are left alone)stray end tags are ignored, unclosed tags are closed at the end
valueless attributes (
disabledbecomesdisabled="") and duplicate attributes (the first one wins, as in browsers)HTML5 character references (all 2231 named ones, legacy ones without a
;, numeric ones) become real characters. In attribute values a legacy reference followed by=or a letter is left alone, so?a=1©=2stays a URL<script>/<style>contents are kept as raw text, and<title>/<textarea>contents are text (entities decoded, no tags inside), as in browsers\r\nand lone\rbecome\n; the newline right after<pre>/<textarea>is dropped (and written back byxml_to_html), exactly as the HTML spec saysa tag cut off by the end of the input is dropped, as browsers do
names XML rejects are mapped reversibly (see below)
newlines and tabs inside attribute values are kept (XML parsers would otherwise turn them into spaces)
comments containing
--, control characters, doctype and<?...?>instructionsfragments with several top-level nodes (or top-level text) are wrapped in a
<root>element; a single top-level element (usually<html>) is used as is
Names XML can’t hold¶
Names such as o:p (a bare prefix breaks namespace-aware parsers) or
@click are mapped, not dropped, and pygixml.xml_to_html() restores
them. The mapping is the SQL/XML one (ISO/IEC 9075-14, “Mapping SQL
identifiers to XML Names”; the same as PostgreSQL’s and .NET’s
XmlConvert.EncodeName), available on its own as
pygixml.encode_name() / pygixml.decode_name(). What counts as a
valid character follows the XML 1.0 name rules, so Unicode letters in names
are kept as they are:
HTML name |
In the XML |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
The mapping is one-to-one: xml_to_html always gets back what was there.
When an encoded name is hard to read, decode it:
>>> doc = pygixml.parse_html("<o:p>t</o:p>")
>>> doc.root.name
'o_x003A_p'
>>> pygixml.decode_name(doc.root.name)
'o:p'
Case of names¶
HTML names are case-insensitive, so by default tag and attribute names are
lower-cased (@Click becomes @click, SVG’s viewBox becomes
viewbox, and two attributes that differ only in case are one). The
case argument of pygixml.html_to_xml() and pygixml.parse_html()
changes that:
|
|
Use it for |
|---|---|---|
|
|
ordinary HTML; |
|
|
Vue/Angular templates, SVG; readable |
|
|
names that must stay lower-case without losing anything |
In every mode text and attribute values are untouched, void tags, implied end
tags and matching end tags still ignore case (<P>a<P>b, <BR>,
<DIV></div>), and pygixml.xml_to_html() gives back the spelling that
the XML holds. With "keep" an end tag takes the spelling of its start tag;
a duplicate attribute (same spelling) keeps the first value.
pygixml.encode_name() has the matching escape_case option, and
pygixml.decode_name() reads all three.
Back to HTML¶
pygixml.xml_to_html() (also node.to_html() and
doc.to_html()) follows HTML rules that to_string() does not:
void tags are written
<br>, empty elements<div></div>(never<div/>, which browsers treat as an open tag)<script>/<style>contents are not escaped (a literal</scriptinside is written<\/scriptso it cannot close the element early)pretty=Trueonly indents block-level structure. Inline elements, text and<pre>/<textarea>/<script>/<style>are never re-indented, so rendering does not change. Likewise no newline is added between top-level nodes if one of them is text or an inline elementthe walk is iterative, so a very deeply nested document cannot overflow the stack (20000 nested
<div>is fine)unwrap="root"drops the wrapper that fragments get when parseddoctype=Trueprepends<!DOCTYPE html>
parse_html keeps whitespace-only text and comments by default (pass
options= to change that), so a tree survives the trip:
html_to_xml(xml_to_html(parse_html(x))) == html_to_xml(x). The output is
a normalised version of the input, not a byte-for-byte copy.
Errors¶
Everything raises pygixml.PygiXMLHTMLError, a subclass of
pygixml.PygiXMLError: input that is not str (decode bytes
first), an empty root name, normalised XML the parser rejects, or a null
or unsupported node given to xml_to_html. HTML itself never fails to
tokenize: like a browser, the C++ tokenizer recovers from anything.
Limitations¶
This is not the HTML5 tree-building algorithm. There are no implied
<html>/<head>/<body> elements, no browser-style table repair,
and tag and attribute names are lower-cased (SVG’s viewBox arrives as
viewbox). That is fine for scraping and data extraction; if you need
browser-exact trees, use a spec-compliant HTML5 parser.
API¶
- pygixml.html_to_xml(html, root='root', case='lower')
Convert HTML (possibly malformed, possibly a fragment) to a well-formed XML string.
Output has exactly one root element. If the input already has exactly one top-level element (typically
<html>) it is used as is; otherwise everything is wrapped in<root>(name configurable via root).Names XML rejects are mapped reversibly (
o:p->o_x003A_p,@click->_x0040_click, seeencode_name()) soxml_to_html()can restore them.HTML names don’t depend on case; case decides what the XML gets:
"lower"(default): tag and attribute names are lower-cased, so<DIV CLASS=a>and//divjust work;"keep": names are written as they were in the input (XML is case sensitive:@Clickand@clickstay two attributes,viewBoxstaysviewBox). The logic (void tags, implied end tags, matching end tags) still ignores case, and an end tag takes the spelling of its start tag;"escape": like"lower", but each upper-case ASCII letter is written as its escape, so nothing is lost and names stay lower-case:@Click->_x0040__x0043_lick.decode_name()reads it.
- Raises:
PygiXMLHTMLError -- html isn’t a
str(decode bytes first), root is empty, or case is not one of the three values.
- pygixml.parse_html(html, root='root', options=None, case='lower')
Parse HTML into an
XMLDocument(seehtml_to_xml()for what is normalised and what is not).The whole conversion runs in C++ in a single call.
options are the usual
ParseFlags. The default keeps whitespace-only text and comments (DEFAULT | WS_PCDATA | COMMENTS): in HTML the space in<b>a</b> <i>b</i>is content, and dropping comments would makexml_to_html()lose them.case is
"lower","keep"or"escape", seehtml_to_xml().- Raises:
PygiXMLHTMLError -- see
html_to_xml(); also if the normalised XML is rejected by the XML parser.
- pygixml.xml_to_html(node, pretty=False, indent=' ', doctype=False, unwrap=None)
Serialize an XML node or document as HTML (the inverse of
parse_html()).Unlike
to_string()this follows HTML rules: void tags are written<br>, empty elements<div></div>(never<div/>, which a browser reads as an open tag),<script>/<style>contents are not escaped, and names encoded byhtml_to_xml()are restored (o_x003A_p->o:p). Runs in a single C++ call.Names are only decoded for a document made by
parse_html()(it remembers where it came from); a document fromparse_string/load_string/load_filekeeps its names exactly. A node follows its document (a node without one, fromfrom_mem_id_unsafe, is decoded).- Parameters:
node -- an
XMLNodeorXMLDocument.pretty -- indent block-level structure. Inline elements, text and
<pre>/<textarea>/<script>/<style>are never re-indented, so rendering doesn’t change.indent (str | int) -- indentation unit when pretty (a string, or a number of spaces).
doctype -- prepend
<!DOCTYPE html>.unwrap (str | None) -- if the only top-level element has this name (typically the
"root"thathtml_to_xml()adds around fragments), emit only its children.
- Raises:
PygiXMLHTMLError -- node isn’t a node/document, or is null.
- pygixml.encode_name(name, fully_escaped=True, escape_case=False)
Map any string to a valid XML name, reversibly (see
decode_name()).This is the SQL/XML rule (ISO/IEC 9075-14, “Mapping SQL identifiers to XML Names”; PostgreSQL’s
map_sql_identifier_to_xml_name, .NET’sXmlConvert.EncodeName). It is whathtml_to_xml()does to the tag and attribute names XML can’t hold. Case is kept.a character that isn’t valid at that place in an XML name becomes
_xHHHH_(its code point, upper-case hex; 6 digits above U+FFFF):@click->_x0040_click,1bad->_x0031_bad;a
_followed byxbecomes_x005F_, so no name can be mistaken for an escape and the mapping is one-to-one;fully_escaped (the default) also escapes every
:(o:p->o_x003A_p) and the first letter of a name starting withxmlin any case (xmlns->_x0078_mlns). WithFalsea:inside a name is kept, giving a QName;escape_case (off by default) also escapes
A-Z(Click->_x0043_lick), for when the name must survive lower-casing.
Names that are already fine (
data-id,snake_case,é) are returned unchanged.- Raises:
PygiXMLHTMLError -- name is not a
str, is empty, or has a lone surrogate.
- pygixml.decode_name(name)
Inverse of
encode_name():_x0040_click->@click.Use it to read the names
parse_html()produced, e.g.decode_name(node.name). Every_x<hex>_of 4 to 8 hex digits that names a real character is replaced (lower-case hex is accepted too); anything else is left alone.
- class pygixml.XMLNameCodec(fully_escaped=True, escape_case=False)
The SQL/XML name mapping as an object, for when the options matter.
>>> c = XMLNameCodec() >>> c.encode("@Click"), c.decode("_x0040_Click") ('_x0040_Click', '@Click') >>> XMLNameCodec(fully_escaped=False).encode("o:p") 'o:p'
fully_escaped and escape_case are described in
encode_name().decodedoes not depend on them.- decode(name)
- encode(name)
encode_name()with this codec’s options.
- exception pygixml.PygiXMLHTMLError
Raised by the HTML helpers: input that isn’t a
str, an empty wrapper name, normalised XML the parser rejects, or a null / unsupported node passed toxml_to_html(). Subclass ofPygiXMLError.
Names on the way back¶
xml_to_html() decodes _xHHHH_ names only for a document
made by parse_html(), which remembers that it came from HTML.
A document from parse_string / load_string / load_file (or one
cleared with reset()) keeps its names exactly. A node follows its
document, so node.to_html() behaves the same way.