0

I am trying to create simple SVG (XML) file as follows:

root = etree.Element('{http://www.w3.org/2000/svg}svg')
root.append(element) # element is a <path> element extracted from another SVG file
print(etree.tostring(root).decode())

But this gives the output as follows:

<ns0:svg xmlns:ns0="http://www.w3.org/2000/svg"><ns0:path ...></ns0:path></ns0:svg>

This output is almost correct, but how do I get rid of the ns0: namespace it seems to have added randomly? The expected output is:

<svg xmlns="http://www.w3.org/2000/svg"><path ...></path></svg>

I've tried using nsmap as follows, but this raises ValueError: Invalid namespace prefix '':

root = etree.Element('{http://www.w3.org/2000/svg}svg', nsmap={'': 'http://www.w3.org/2000/svg'})
# ...

This answer comes close, but it removes the namespace prefix and the namespace, which I don't really want – I want to remove the namespace prefix, but preserve the namespace (as it wouldn't be a valid SVG without the namespace).

Sumit
  • 2,242
  • 1
  • 24
  • 37

1 Answers1

0

You're close. In nsmap=, instead of '', use None:

root = etree.Element('{http://www.w3.org/2000/svg}svg', nsmap={None: 'http://www.w3.org/2000/svg'})
root.append(element) # element is a <path> element extracted from another SVG file
print(etree.tostring(root).decode())

This will preserve the namespace, but not add any namespace prefix (i.e. ns0).

Sumit
  • 2,242
  • 1
  • 24
  • 37