26

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?

jfenwick
  • 1,319
  • 15
  • 17

2 Answers2

56

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.

jfenwick
  • 1,319
  • 15
  • 17
  • 16
    Answering your own question is much better than deleting it. If someone later has this question, it will already be answered and indexed! – codekaizen Oct 09 '10 at 06:47
  • If you need compatibility with older Pythons (or even if you don't), you might be better off using [`lxml.etree`](http://codespeak.net/lxml/tutorial.html): this is more or less a superset of what's provided by `xml.etree`. Has some external dependencies, though. – intuited Oct 09 '10 at 06:51
  • lxml is notorious for not working on OS X out of the box. They don't provide a precompiled egg for Intel macs and trying to compile it from scratch is extremely hard. The only way to get it working quickly is if you're using macports, which I don't feel is an acceptable dependency. – jfenwick Oct 09 '10 at 17:13
  • 11
    As someone who googled `python xml ns0` and got your answer, I'm pretty grateful this wasn't deleted ;) – Conrad.Dean Oct 30 '12 at 16:59
  • Some extra info: if you are using a different namespace in your xml, you obviously need to change the url in the register_namespace call to match your namespace. – Joris May 03 '13 at 13:15
  • 1
    @jfenwick, where in your code (after which line) do you put the `register-namespace` method? – sbru Sep 19 '14 at 22:52
  • @sbru, sorry for being 9 years later, but `import xml.etree.ElementTree as et; et.register_namespace("", "http://www.w3.org/2000/svg")` is what I did to make it work in python 3. – Shmack Jun 15 '23 at 07:39
0

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

Community
  • 1
  • 1
Al Conrad
  • 1,528
  • 18
  • 12