[Python-Dev] c/ElementTree XML serialisation

Alex Leach albl500 at york.ac.uk
Tue May 8 18:21:38 CEST 2012


Hi, 

I was just reading through the ElementTree source code, in order to figure
out how I might override the serialisation on the text nodes of <script>
and <style> elements. It doesn't appear I can do that with Element
instances though.

I'm making an SVG generating tool, and because SVG uses the XML namespace,
[c]ElementTree serialises 'script' Elements like any other XML Element.
However, if I was using the HTML namespace instead, I wouldn't suffer from
this, because of the following clause, which is missing from the XML
serialiser:-

if tag=="script" or tag == "style":
    write(_encode(text, encoding) )
else:
    write(_escape_cdata(text, encoding) )

The w3c SVG specification / recommendation
<http://www.w3.org/TR/SVG/script.html> allows for <script> and <style>
tags, recommending to wrap the text node in a <![CDATA[ … ]]>. Pretty
standard.

I'm not sure if other XML namespaces have need for script and style
sections, but it's definitely a problem when generating SVG, as I'll have
to un-replace all the replace's in ElementTree.py's _escape_cdata
function. Knowingly doing that makes me cringe, but I think it's what I'll
have to do...

Is there a better way?

Cheers,
Alex





More information about the Python-Dev mailing list