pythonxmlsvgelementtreeprefix

Add prefixed attribute in ElementTree


I am manipulating SVG files in ElementTree. Given the file test.svg

<?xml version='1.0' encoding='utf-8'?>
<svg 
  xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>

I tried to create an element with specific prefix

import xml.etree.ElementTree as ET
ET.register_namespace("", "http://www.w3.org/2000/svg")
tree = ET.parse('test.svg')
tree.getroot().set("xmlns:xlink", "http://www.w3.org/1999/xlink")
link = ET.fromstring('<a xlink:href="http://www.example.com/"></a>')
tree.write('test_out.svg', encoding = 'utf-8', xml_declaration = True)

but run into a unbound prefix error. I've looked through this tutorial but can't quite see what's wrong.


Solution

  • You have to declare xlink also in the string which you parse with fromstring:

    link = ET.fromstring('<a xmlns:xlink="http://www.w3.org/1999/xlink" '
                         'xlink:href="http://www.mysite.com/"></a>')