Python 3.8+xml.etree.ElementTreefunction
xml.etree.ElementTree.canonicalize()
canonicalization
Converts XML to the C14N 2.0 canonical form so two documents can be compared byte by byte. Returns a str or writes to out.
Syntax
ET.canonicalize(xml_data=None, *, out=None, from_file=None, **options)
Canonicalization sorts attributes, expands empty tags <b/> into <b></b> and drops the declaration; comparing two XML documents as plain strings without it gives false differences. Whitespace between tags is significant by default: strip_text=True trims it. Comments are dropped unless with_comments=True. The result is a str (not bytes, unlike tostring), and a file passed as out is opened in text mode with utf-8.
Examples
import xml.etree.ElementTree as ET
a = '<r z="1" a="2"><b/></r>'
b = '<r a="2" z="1"><b></b></r>'
print(a == b, ET.canonicalize(a) == ET.canonicalize(b)) # → False True
print(ET.canonicalize(a)) # → <r a="2" z="1"><b></b></r>
print(ET.canonicalize('<r> <b>t</b> </r>', strip_text=True)) # → <r><b>t</b></r>
See also
Open in the full glossarydocs.python.orgReport an inaccuracy