Create SVG / XML document without ns0 namespace using Python ElementTree


Question

I'm building an SVG document with ElementTree in Python 2.7. Here is the code:

from xml.etree import ElementTree as etree

root = etree.XML('<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg"></svg>')
root.append(etree.Element("path"))
root[0].set("d", "M1 1 L2 2 Z")
print etree.tostring(root, encoding='iso-8859-1')

This generates the output:

<?xml version='1.0' encoding='iso-8859-1'?>
<ns0:svg xmlns:ns0="http://www.w3.org/2000/svg" height="100%" version="1.1" width="100%"><path d="M1 1 L2 2 Z" /></ns0:svg>

This does not parse as valid SVG. How can I remove the ns0 namespace?

1
22
10/9/2010 6:32:13 AM

Accepted Answer

I just figured it out and I can't delete the question so here it is:

etree.register_namespace("","http://www.w3.org/2000/svg")

I think this only works as of Python 2.7 though.

48
10/9/2010 6:37:36 AM

Here's how I do it with lxml.

from lxml import etree
svg_tree = etree.fromstring(svg_str, parser=etree.XMLParser())
etree.tostring(svg_tree)

Used sample code from here: lxml-removing-xml-tags-when-parsing


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon