Search code examples
pythonxmlsax

how to use xml.sax.saxutils.XMLGenerator to write an element with a namespace


I've used XMLGenerator to write things but can't seem to figure out how to use namsepaces. I keep getting KeyErrors.

Just as a quick example I would like to write

<svg width="120" height="120"
     viewBox="0 0 120 120"
     xmlns="http://www.w3.org/2000/svg">

  <rect x="10" y="10"
        width="100" height="100"
        rx="15" ry="15"/>

</svg>

How should I call startElementNS?

xmlgen.startElementNS(('http://www.w3.org/2000/svg','svg'),'svg',{})

gives me this error:

  File "c:\app\python\anaconda\1.6.0\envs\emblaze\lib\xml\sax\saxutils.py", line 169, in startElementNS
    self._write(u'<' + self._qname(name))
  File "c:\app\python\anaconda\1.6.0\envs\emblaze\lib\xml\sax\saxutils.py", line 134, in _qname
    prefix = self._current_context[name[0]]
KeyError: 'http://www.w3.org/2000/svg'

Solution

  • Looking at the docs seems to suggest you need something like:

    from tempfile import TemporaryFile
    f = TemporaryFile()
    ns = "http://www.w3.org/2000/svg"
    xmlgen = XMLGenerator(f)
    xmlgen.startDocument()
    xmlgen.startPrefixMapping("ns1", ns)
    xmlgen.startElementNS((ns, "svg"), "ns1:svg", {})
    f.seek(0)
    print(f.read())
    
    <?xml version="1.0" encoding="iso-8859-1"?>
    <ns1:svg xmlns:ns1="http://www.w3.org/2000/svg">

    The xmlgen.startPrefixMapping seems to be necessary.