[New-bugs-announce] [issue5027] xml namespace not understood by xml.sax.saxutils.XMLGenerator

Soren Roug report at bugs.python.org
Wed Jan 21 21:59:42 CET 2009

New submission from Soren Roug <soren.roug at eea.europa.eu>:

The 'xml' namespace in XML files is special in that it need not be
declared. When xml.sax.saxutils.XMLGenerator is used with the namespace
feature it does not know how to handle it.

Example. The code:

import xml.sax, xml.sax.saxutils
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_namespaces, 1)
c = xml.sax.saxutils.XMLGenerator()

executed on the testfile.xml with this content:

<?xml version="1.0"?>
<a:greetings xmlns:a="http://example.com/ns">
  <a:greet xml:lang="en">Hello world</a:greet>

will produce this error:
  File "/usr/lib/python2.5/xml/sax/saxutils.py", line 149, in startElementNS
    self._write(' %s=%s' % (self._qname(name), quoteattr(value)))
  File "/usr/lib/python2.5/xml/sax/saxutils.py", line 107, in _qname
    prefix = self._current_context[name[0]]
KeyError: u'http://www.w3.org/XML/1998/namespace'

It can be fixed by making an exception for the xml namespace (as
required by W3C - See http://www.w3.org/XML/1998/namespace) in
xml/sax/saxutils.py. The _qname method could then look like this:

    def _qname(self, name):
        """Builds a qualified name from a (ns_url, localname) pair"""
        if name[0]:
            if name[0] == u'http://www.w3.org/XML/1998/namespace':
                return u'xml' + ":" + name[1]
            # The name is in a non-empty namespace
            prefix = self._current_context[name[0]]
            if prefix:
                # If it is not the default namespace, prepend the prefix
                return prefix + ":" + name[1]
        # Return the unqualified name
        return name[1]

components: Library (Lib), XML
messages: 80346
nosy: roug
severity: normal
status: open
title: xml namespace not understood by xml.sax.saxutils.XMLGenerator
type: behavior
versions: Python 2.5

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list