1from __future__ import absolute_import, division, unicode_literals 2 3from xml.sax.xmlreader import AttributesNSImpl 4 5from ..constants import adjustForeignAttributes, unadjustForeignAttributes 6 7prefix_mapping = {} 8for prefix, localName, namespace in adjustForeignAttributes.values(): 9 if prefix is not None: 10 prefix_mapping[prefix] = namespace 11 12 13def to_sax(walker, handler): 14 """Call SAX-like content handler based on treewalker walker""" 15 handler.startDocument() 16 for prefix, namespace in prefix_mapping.items(): 17 handler.startPrefixMapping(prefix, namespace) 18 19 for token in walker: 20 type = token["type"] 21 if type == "Doctype": 22 continue 23 elif type in ("StartTag", "EmptyTag"): 24 attrs = AttributesNSImpl(token["data"], 25 unadjustForeignAttributes) 26 handler.startElementNS((token["namespace"], token["name"]), 27 token["name"], 28 attrs) 29 if type == "EmptyTag": 30 handler.endElementNS((token["namespace"], token["name"]), 31 token["name"]) 32 elif type == "EndTag": 33 handler.endElementNS((token["namespace"], token["name"]), 34 token["name"]) 35 elif type in ("Characters", "SpaceCharacters"): 36 handler.characters(token["data"]) 37 elif type == "Comment": 38 pass 39 else: 40 assert False, "Unknown token type" 41 42 for prefix, namespace in prefix_mapping.items(): 43 handler.endPrefixMapping(prefix) 44 handler.endDocument() 45