Index: Lib/test/test_sax.py =================================================================== --- Lib/test/test_sax.py (revision 83808) +++ Lib/test/test_sax.py (working copy) @@ -11,6 +11,7 @@ from xml.sax.saxutils import XMLGenerator, escape, unescape, quoteattr, \ XMLFilterBase from xml.sax.expatreader import create_parser +from xml.sax.handler import feature_namespaces from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl from io import StringIO from test.support import findfile, run_unittest @@ -295,7 +296,60 @@ self.assertEquals(result.getvalue(), start+'') + def test_5027_1(self): + # The xml prefix (as in xml:lang below) is reserved and bound by + # definition to http://www.w3.org/XML/1998/namespace. XMLGenerator has + # a bug whereby a KeyError is thrown because this namespace is missing + # from a dictionary. + # + # This test demonstrates the bug by parsing a document. + test_xml = StringIO( + '' + '' + 'Hello' + '') + parser = make_parser() + parser.setFeature(feature_namespaces, True) + result = StringIO() + gen = XMLGenerator(result) + parser.setContentHandler(gen) + parser.parse(test_xml) + + self.assertEquals(result.getvalue(), + start + ( + '' + 'Hello' + '')) + + def test_5027_2(self): + # The xml prefix (as in xml:lang below) is reserved and bound by + # definition to http://www.w3.org/XML/1998/namespace. XMLGenerator has + # a bug whereby a KeyError is thrown because this namespace is missing + # from a dictionary. + # + # This test demonstrates the bug by direct manipulation of the + # XMLGenerator. + result = StringIO() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping('a', 'http://example.com/ns') + gen.startElementNS(('http://example.com/ns', 'g1'), 'g1', {}) + lang_attr = {('http://www.w3.org/XML/1998/namespace', 'lang'): 'en'} + gen.startElementNS(('http://example.com/ns', 'g2'), 'g2', lang_attr) + gen.characters('Hello') + gen.endElementNS(('http://example.com/ns', 'g2'), 'g2') + gen.endElementNS(('http://example.com/ns', 'g1'), 'g1') + gen.endPrefixMapping('a') + gen.endDocument() + + self.assertEquals(result.getvalue(), + start + ( + '' + 'Hello' + '')) + class XMLFilterBaseTest(unittest.TestCase): def test_filter_basic(self): result = StringIO() Index: Lib/xml/sax/saxutils.py =================================================================== --- Lib/xml/sax/saxutils.py (revision 83808) +++ Lib/xml/sax/saxutils.py (working copy) @@ -98,6 +98,12 @@ def _qname(self, name): """Builds a qualified name from a (ns_url, localname) pair""" if name[0]: + # Per http://www.w3.org/XML/1998/namespace, The 'xml' prefix is + # bound by definition to http://www.w3.org/XML/1998/namespace. It + # does not need to be declared and will not usually be found in + # self._current_context. + if 'http://www.w3.org/XML/1998/namespace' == name[0]: + return 'xml:' + name[1] # The name is in a non-empty namespace prefix = self._current_context[name[0]] if prefix: