-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathelementflow.py
236 lines (191 loc) · 7.7 KB
/
elementflow.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# -*- coding:utf-8 -*-
'''
Library for generating XML as a stream without first building a tree in memory.
Basic usage::
import elementflow
file = open('text.xml', 'w') # can be any object with .write() method
with elementflow.xml(file, u'root') as xml:
xml.element(u'item', attrs={u'key': u'value'}, text=u'text')
with xml.container(u'container', attrs={u'key': u'value'}):
xml.text(u'text')
xml.element(u'subelement', text=u'subelement text')
Usage with namespaces::
with elementflow.xml(file, 'root', namespaces={'': 'urn:n', 'n1': 'urn:n1'}) as xml:
xml.element('item')
with xml.container('container', namespaces={'n2': 'urn:n2'):
xml.element('n1:subelement')
xml.element('n2:subelement')
Pretty-printing::
with elementflow.xml(file, 'root', indent=True):
# ...
'''
import textwrap
import codecs
import six
def escape(value):
if '&' not in value and '<' not in value:
return value
return value.replace('&', '&').replace('<', '<')
def quoteattr(value):
if '&' in value or '<' in value or '"' in value:
value = value.replace('&', '&').replace('<', '<').replace('"', '"')
return u'"%s"' % value
def attr_str(attrs):
if not attrs:
return u''
return u''.join([u' %s=%s' % (k, quoteattr(v)) for k, v in six.iteritems(attrs)])
class XMLGenerator(object):
'''
Basic generator without support for namespaces or pretty-printing.
Constructor accepts:
- file: an object receiving XML output, anything with .write()
- root: name of the root element
- attrs: attributes dict
Constructor will implicitly open a root container element, you don't need
to call .container() for it
'''
def __init__(self, file, root, attrs={}, **kwargs):
self.file = codecs.getwriter('utf-8')(file)
self.file.write(u'<?xml version="1.0" encoding="utf-8"?>')
self.stack = []
self.container(root, attrs, **kwargs)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
if exc_type:
return
self.file.write(u'</%s>' % self.stack.pop())
def container(self, name, attrs={}):
'''
Opens a new element containing sub-elements and text nodes.
Intends to be used under ``with`` statement.
'''
self.file.write(u'<%s%s>' % (name, attr_str(attrs)))
self.stack.append(name)
return self
def element(self, name, attrs={}, text=u''):
'''
Generates a single element, either empty or with a text contents.
'''
if text:
self.file.write(u'<%s%s>%s</%s>' % (name, attr_str(attrs), escape(text), name))
else:
self.file.write(u'<%s%s/>' % (name, attr_str(attrs)))
def text(self, value):
'''
Generates a text in currently open container.
'''
self.file.write(escape(value))
def comment(self, value):
'''
Adds a comment to the xml
'''
value = value.replace('--','')
self.file.write(u'<!--%s-->' % value)
def map(self, func, sequence):
'''
Convenience function for translating a sequence of objects into xml elements.
First parameter is a function that accepts an object from the sequence and
return a tuple of arguments for "element" method.
'''
for item in sequence:
self.element(*func(item))
class NamespacedGenerator(XMLGenerator):
'''
XML generator with support for namespaces.
'''
def __init__(self, file, root, attrs={}, namespaces={}):
self.namespaces = [set(['xml'])]
super(NamespacedGenerator, self).__init__(file, root, attrs=attrs, namespaces=namespaces)
def _process_namespaces(self, name, attrs, namespaces):
prefixes = self.namespaces[-1]
if namespaces:
prefixes |= set(namespaces.keys())
names = [n for n in [name] + list(attrs.keys()) if ':' in n]
for name in names:
prefix = name.split(':')[0]
if prefix not in prefixes:
raise ValueError('Unkown namespace prefix: %s' % prefix)
if namespaces:
namespaces = dict([
(u'xmlns:%s' % k if k else u'xmlns', v)
for k, v in six.iteritems(namespaces)
])
attrs = dict(attrs, **namespaces)
return attrs, prefixes
def __exit__(self, exc_type, exc_value, exc_tb):
super(NamespacedGenerator, self).__exit__(exc_type, exc_value, exc_tb)
self.namespaces.pop()
def container(self, name, attrs={}, namespaces={}):
attrs, prefixes = self._process_namespaces(name, attrs, namespaces)
self.namespaces.append(prefixes)
return super(NamespacedGenerator, self).container(name, attrs)
def element(self, name, attrs={}, namespaces={}, text=u''):
attrs, prefixes = self._process_namespaces(name, attrs, namespaces)
super(NamespacedGenerator, self).element(name, attrs, text)
class IndentingGenerator(NamespacedGenerator):
'''
XML generator with pretty-printing.
'''
def __init__(self, *args, **kwargs):
self._text_wrap = kwargs.pop('text_wrap', True)
super(IndentingGenerator, self).__init__(*args, **kwargs)
def _format_value(self, value):
indent = u' ' * len(self.stack)
self.file.write(u'\n%s' % indent)
if len(value) > 70 and self._text_wrap:
fill = self._fill(value, indent + u' ')
value = u'%s\n%s' % (fill, indent)
return value
def _fill(self, value, indent=None):
if indent is None:
indent = u' ' * len(self.stack)
width = max(20, 70 - len(indent))
tw = textwrap.TextWrapper(width=width, initial_indent=indent, subsequent_indent=indent)
return u'\n%s' % tw.fill(value)
def __exit__(self, *args, **kwargs):
self.file.write(u'\n%s' % (u' ' * (len(self.stack) - 1)))
super(IndentingGenerator, self).__exit__(*args, **kwargs)
if not self.stack:
self.file.write(u'\n')
def container(self, *args, **kwargs):
self.file.write(u'\n%s' % (u' ' * len(self.stack)))
return super(IndentingGenerator, self).container(*args, **kwargs)
def element(self, name, attrs={}, namespaces={}, text=u''):
text = self._format_value(text)
return super(IndentingGenerator, self).element(name, attrs, namespaces, text)
def text(self, value):
super(IndentingGenerator, self).text(self._fill(value))
def comment(self, value):
value = self._format_value(value)
return super(IndentingGenerator, self).comment(value)
class Queue(object):
'''
In-memory queue for using as a temporary buffer in xml generator.
'''
def __init__(self):
self.data = bytearray()
def __len__(self):
return len(self.data)
def write(self, value):
self.data.extend(value)
def pop(self):
result = str(self.data)
self.data = bytearray()
return result
def xml(file, root, attrs={}, namespaces={}, indent=False, text_wrap=True):
'''
Creates a streaming XML generator.
Parameters:
- file: an object receiving XML output, anything with .write()
- root: name of the root element
- attrs: attributes dict
- namespaces: namespaces dict {prefix: uri}, default namespace has prefix ''
- indent: whether to pretty-print XML, True or False (default)
'''
if indent:
return IndentingGenerator(file, root, attrs, namespaces, text_wrap=text_wrap)
elif namespaces:
return NamespacedGenerator(file, root, attrs, namespaces)
else:
return XMLGenerator(file, root, attrs)