File: etree.py

package info (click to toggle)
svgwrite 1.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 2,092 kB
  • sloc: python: 12,603; makefile: 117; sh: 5
file content (49 lines) | stat: -rw-r--r-- 1,312 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env python
#coding:utf-8
# Author:  mozman
# Purpose: a hack to generate XML containing CDATA by ElementTree
# Created: 26.05.2012
# Copyright (C) 2012, Manfred Moitzi
# License: MIT License

# usage:
#
# from svgwrite.etree import etree, CDATA
#
# element = etree.Element('myTag')
# element.append(CDATA("< and >"))
#
# assert etree.tostring(element) == "<myTag><![CDATA[< and >]]></myTag>"


import sys
PY3 = sys.version_info[0] > 2

import xml.etree.ElementTree as etree

CDATA_TPL = "<![CDATA[%s]]>"
CDATA_TAG = CDATA_TPL


def CDATA(text):
    element = etree.Element(CDATA_TAG)
    element.text = text
    return element

original_serialize_xml = etree._serialize_xml

if PY3:
    def _serialize_xml_with_CDATA_support(write, elem, qnames, namespaces, **kwargs):
        if elem.tag == CDATA_TAG:
            write(CDATA_TPL % elem.text)
        else:
            original_serialize_xml(write, elem, qnames, namespaces, **kwargs)
else:
    def _serialize_xml_with_CDATA_support(write, elem, encoding, qnames, namespaces):
        if elem.tag == CDATA_TAG:
            write(CDATA_TPL % elem.text.encode(encoding))
        else:
            original_serialize_xml(write, elem, encoding, qnames, namespaces)

# ugly, ugly, ugly patching
etree._serialize_xml = _serialize_xml_with_CDATA_support