1 """ElementTree helper functions
5 LOGGER = logging.getLogger(__name__)
9 def indent(elem, level=0):
11 reformat an element tree to be 'pretty' (indented)
15 if not elem.text or not elem.text.strip():
18 indent(child, level+1)
19 # we don't want the closing tag indented too far
21 if not elem.tail or not elem.tail.strip():
24 if level and (not elem.tail or not elem.tail.strip()):
27 def flatten(elem, include_tail=0):
29 Extract the text from an element tree
30 (AKA extract the text that not part of XML tags)
32 text = elem.text or ""
35 if include_tail and elem.tail: text += elem.tail
38 def validate_xhtml(html, base_url='http://localhost'):
39 """Helper for validating xhtml, mostly intended for test code
41 Defaults to assuming XHTML+RDFa
42 Returns None if there was a problem configuring validation
43 Logs messages from lxml.etree using python logging
44 Returns True if it passed validation
45 and False if it fails.
48 XHTML_RDF_DTD = lxml.etree.DTD(external_id='-//W3C//DTD XHTML+RDFa 1.0//EN')
49 except lxml.etree.DTDParseError as e:
50 LOGGER.warn("Unable to load XHTML DTD %s" % (str(e),))
54 root = lxml.etree.fromstring(html, base_url=base_url)
55 except lxml.etree.ParseError as e:
56 LOGGER.warn("Unable to parse document: %s" % (str(e),))
59 if XHTML_RDF_DTD.validate(root):
64 for msg in XHTML_RDF_DTD.error_log.filter_from_errors():
65 # I have no idea how to suppress this error
66 # but I need the xmlns attributes for of my RDFa 1.0 encoding
67 if 'ERROR:VALID:DTD_UNKNOWN_ATTRIBUTE' in str(msg):