1
|
# XML DOM tree manipulation
|
2
|
|
3
|
import cgi
|
4
|
from HTMLParser import HTMLParser
|
5
|
import itertools
|
6
|
import re
|
7
|
from xml.dom import Node
|
8
|
import xml.dom.minidom as minidom
|
9
|
|
10
|
import strings
|
11
|
import util
|
12
|
|
13
|
##### Escaping input
|
14
|
|
15
|
def escape(str_):
|
16
|
return strings.to_unicode(cgi.escape(str_, True)).encode('ascii',
|
17
|
'xmlcharrefreplace')
|
18
|
|
19
|
def unescape(str_): return HTMLParser().unescape(str_)
|
20
|
|
21
|
##### Names
|
22
|
|
23
|
def strip_namespace(name):
|
24
|
namespace, sep, base = name.partition(':')
|
25
|
if sep != '': return base
|
26
|
else: return name
|
27
|
|
28
|
##### Nodes
|
29
|
|
30
|
def is_node(value): return isinstance(value, Node)
|
31
|
|
32
|
##### Replacing a node
|
33
|
|
34
|
def remove(node): node.parentNode.removeChild(node)
|
35
|
|
36
|
def replace(old, new):
|
37
|
'''@param new Node|None'''
|
38
|
assert old.parentNode != None # not removed from parent tree
|
39
|
|
40
|
if new == None: old.parentNode.removeChild(old)
|
41
|
else: old.parentNode.replaceChild(new, old) # note order reversed
|
42
|
|
43
|
def bool2str(val):
|
44
|
'''For use with replace_with_text()'''
|
45
|
if val: return '1'
|
46
|
else: return None # remove node
|
47
|
|
48
|
def replace_with_text(node, new):
|
49
|
'''
|
50
|
@return The *new* node
|
51
|
'''
|
52
|
if isinstance(new, bool): new = bool2str(new)
|
53
|
if util.is_str(new): new = node.ownerDocument.createTextNode(new)
|
54
|
replace(node, new)
|
55
|
return new
|
56
|
|
57
|
##### Element node contents
|
58
|
|
59
|
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
|
60
|
|
61
|
def is_completely_empty(node): return node.firstChild == None
|
62
|
|
63
|
def has_one_child(node):
|
64
|
return node.firstChild != None and node.firstChild.nextSibling == None
|
65
|
|
66
|
def is_simple(node):
|
67
|
'''Whether every child recursively has no more than one child'''
|
68
|
return (not is_elem(node) or is_completely_empty(node)
|
69
|
or (has_one_child(node) and is_simple(node.firstChild)))
|
70
|
|
71
|
class NodeIter:
|
72
|
def __init__(self, node): self.child = node.firstChild
|
73
|
|
74
|
def __iter__(self): return self
|
75
|
|
76
|
def curr(self):
|
77
|
if self.child != None: return self.child
|
78
|
raise StopIteration
|
79
|
|
80
|
def next(self):
|
81
|
child = self.curr()
|
82
|
self.child = self.child.nextSibling
|
83
|
return child
|
84
|
|
85
|
##### Comments
|
86
|
|
87
|
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
|
88
|
|
89
|
def is_empty(node):
|
90
|
for child in NodeIter(node):
|
91
|
if not (is_whitespace(child) or is_comment(child)): return False
|
92
|
return True
|
93
|
|
94
|
def clean_comment(str_):
|
95
|
'''Sanitizes comment node contents. Strips invalid strings.'''
|
96
|
return re.sub(r'-{2,}', r'-', str_) # comments can't contain '--'
|
97
|
|
98
|
def mk_comment(doc, str_): return doc.createComment(clean_comment(str_))
|
99
|
|
100
|
##### Child nodes that are elements
|
101
|
|
102
|
class NodeElemIter:
|
103
|
def __init__(self, node): self.child = node.firstChild
|
104
|
|
105
|
def __iter__(self): return self
|
106
|
|
107
|
def curr(self):
|
108
|
while self.child != None:
|
109
|
if is_elem(self.child): return self.child
|
110
|
self.child = self.child.nextSibling
|
111
|
raise StopIteration
|
112
|
|
113
|
def next(self):
|
114
|
child = self.curr()
|
115
|
self.child = self.child.nextSibling
|
116
|
return child
|
117
|
|
118
|
def first_elem(node): return NodeElemIter(node).next()
|
119
|
|
120
|
def has_elems(node):
|
121
|
try: first_elem(node); return True
|
122
|
except StopIteration: return False
|
123
|
|
124
|
class NodeElemReverseIter:
|
125
|
def __init__(self, node): self.child = node.lastChild
|
126
|
|
127
|
def __iter__(self): return self
|
128
|
|
129
|
def curr(self):
|
130
|
while self.child != None:
|
131
|
if is_elem(self.child): return self.child
|
132
|
self.child = self.child.previousSibling
|
133
|
raise StopIteration
|
134
|
|
135
|
def next(self):
|
136
|
child = self.curr()
|
137
|
self.child = self.child.previousSibling
|
138
|
return child
|
139
|
|
140
|
def last_elem(node): return NodeElemReverseIter(node).next()
|
141
|
|
142
|
class NodeEntryIter:
|
143
|
def __init__(self, node): self.iter_ = NodeElemIter(node)
|
144
|
|
145
|
def __iter__(self): return self
|
146
|
|
147
|
def next(self):
|
148
|
entry = self.iter_.next()
|
149
|
if is_empty(entry): value = None
|
150
|
else:
|
151
|
assert has_one_child(entry) # TODO: convert to an exception
|
152
|
value = entry.firstChild
|
153
|
return (entry.tagName, value)
|
154
|
|
155
|
##### Parent nodes
|
156
|
|
157
|
def parent(node):
|
158
|
'''Does not treat the document object as the root node's parent, since it's
|
159
|
not a true element node'''
|
160
|
parent_ = node.parentNode
|
161
|
if parent_ != None and is_elem(parent_): return parent_
|
162
|
else: return None
|
163
|
|
164
|
class NodeParentIter:
|
165
|
'''See parent() for special treatment of root node.
|
166
|
Note that the first element returned is the current node, not its parent.'''
|
167
|
def __init__(self, node): self.node = node
|
168
|
|
169
|
def __iter__(self): return self
|
170
|
|
171
|
def curr(self):
|
172
|
if self.node != None: return self.node
|
173
|
else: raise StopIteration
|
174
|
|
175
|
def next(self):
|
176
|
node = self.curr()
|
177
|
self.node = parent(self.node)
|
178
|
return node
|
179
|
|
180
|
##### Element nodes containing text
|
181
|
|
182
|
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
|
183
|
|
184
|
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
|
185
|
|
186
|
def value_node(node):
|
187
|
if is_elem(node):
|
188
|
iter_ = NodeIter(node)
|
189
|
util.skip(iter_, is_comment)
|
190
|
try: return iter_.next()
|
191
|
except StopIteration: return None
|
192
|
else: return node
|
193
|
|
194
|
def value(node):
|
195
|
value_ = util.do_ignore_none(lambda n: n.nodeValue, value_node(node))
|
196
|
if value_ == strings.isspace_none_str: value_ = None # None equiv
|
197
|
return value_
|
198
|
|
199
|
def is_whitespace(node):
|
200
|
return is_text_node(node) and (node.nodeValue == ''
|
201
|
or node.nodeValue.isspace())
|
202
|
|
203
|
def set_value(node, value):
|
204
|
value_node_ = value_node(node)
|
205
|
if value != None:
|
206
|
if value_node_ != None:
|
207
|
value_node_.nodeValue = value
|
208
|
else:
|
209
|
assert is_elem(node)
|
210
|
node.appendChild(node.ownerDocument.createTextNode(value))
|
211
|
elif value_node_ != None:
|
212
|
if is_elem(node): remove(value_node_)
|
213
|
else:
|
214
|
if is_text_node(node): value = strings.isspace_none_str # None equiv
|
215
|
node.nodeValue = value
|
216
|
|
217
|
class NodeTextEntryIter:
|
218
|
def __init__(self, node): self.iter_ = NodeElemIter(node)
|
219
|
|
220
|
def __iter__(self): return self
|
221
|
|
222
|
def next(self):
|
223
|
entry = self.iter_.next()
|
224
|
if is_empty(entry): value_ = None
|
225
|
elif is_text(entry): value_ = value(entry)
|
226
|
else:
|
227
|
assert has_one_child(entry) # TODO: convert to an exception
|
228
|
value_ = entry.firstChild
|
229
|
return (entry.tagName, value_)
|
230
|
|
231
|
def is_text_node_entry(val): return util.is_str(val[1])
|
232
|
|
233
|
def non_empty(iterable):
|
234
|
return itertools.ifilter(lambda i: i[1] != None, iterable)
|
235
|
|
236
|
class TextEntryOnlyIter(util.CheckedIter):
|
237
|
def __init__(self, iterable):
|
238
|
util.CheckedIter.__init__(self, is_text_node_entry, non_empty(iterable))
|
239
|
|
240
|
##### IDs
|
241
|
|
242
|
def get_id(node):
|
243
|
'''If the node doesn't have an ID, assumes the node itself is the ID.
|
244
|
@return None if the node doesn't have an ID or a value
|
245
|
'''
|
246
|
id_ = node.getAttribute('id')
|
247
|
if id_ != '': return id_
|
248
|
else: return value(node) # assume the node itself is the ID
|
249
|
|
250
|
def set_id(node, id_): node.setAttribute('id', id_)
|
251
|
|
252
|
##### Child nodes
|
253
|
|
254
|
def prune_empty(node):
|
255
|
'''Removes node if it's empty'''
|
256
|
if is_empty(node): remove(node)
|
257
|
|
258
|
def prune_children(node):
|
259
|
'''Removes empty children'''
|
260
|
for child in NodeElemIter(node): prune_empty(child)
|
261
|
|
262
|
def prune(node):
|
263
|
'''Removes empty children and then node if it's empty'''
|
264
|
prune_children(node)
|
265
|
prune_empty(node)
|
266
|
|
267
|
def set_child(node, name, value):
|
268
|
'''Note: does not remove any existing child of the same name'''
|
269
|
child = node.ownerDocument.createElement(name)
|
270
|
set_value(child, value)
|
271
|
node.appendChild(child)
|
272
|
|
273
|
def by_tag_name(node, name, last_only=False, ignore_namespace=False):
|
274
|
'''last_only optimization returns only the last matching node'''
|
275
|
if ignore_namespace: filter_name = strip_namespace
|
276
|
else: filter_name = lambda name: name
|
277
|
name = filter_name(name)
|
278
|
|
279
|
children = []
|
280
|
if last_only: iter_ = NodeElemReverseIter(node)
|
281
|
else: iter_ = NodeElemIter(node)
|
282
|
for child in iter_:
|
283
|
if filter_name(child.tagName) == name:
|
284
|
children.append(child)
|
285
|
if last_only: break
|
286
|
return children
|
287
|
|
288
|
def merge(from_, into):
|
289
|
'''Merges two nodes of the same tag name and their newly-adjacent children.
|
290
|
@post The into node is saved; the from_ node is deleted.
|
291
|
'''
|
292
|
if from_ == None or into == None: return # base case
|
293
|
if from_.tagName != into.tagName: return # not mergeable
|
294
|
|
295
|
from_first = from_.firstChild # save before merge
|
296
|
for child in NodeIter(from_): into.appendChild(child)
|
297
|
remove(from_)
|
298
|
|
299
|
# Recurse
|
300
|
merge(from_first, from_first.previousSibling) # = into.lastChild
|
301
|
|
302
|
def merge_by_name(root, name):
|
303
|
'''Merges siblings in root with the given name'''
|
304
|
children = by_tag_name(root, name)
|
305
|
child0 = children.pop(0)
|
306
|
for child in children: merge(child, child0)
|
307
|
|
308
|
##### XML documents
|
309
|
|
310
|
def create_doc(root='_'):
|
311
|
return minidom.getDOMImplementation().createDocument(None, root, None)
|
312
|
|
313
|
##### Printing XML
|
314
|
|
315
|
prettyxml_config = dict(addindent=' ', newl='\n')
|
316
|
toprettyxml_config = prettyxml_config.copy()
|
317
|
util.rename_key(toprettyxml_config, 'addindent', 'indent')
|
318
|
|
319
|
##### minidom modifications
|
320
|
|
321
|
#### Module
|
322
|
|
323
|
minidom._write_data = lambda writer, data: writer.write(escape(data))
|
324
|
|
325
|
minidom.Node.__iter__ = lambda self: NodeIter(self)
|
326
|
|
327
|
def __Node_str(self):
|
328
|
return strings.remove_extra_newl(self.toprettyxml(**toprettyxml_config))
|
329
|
minidom.Node.__str__ = __Node_str
|
330
|
minidom.Node.__repr__ = __Node_str
|
331
|
minidom.Element.__repr__ = __Node_str
|
332
|
|
333
|
#### Node
|
334
|
|
335
|
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
|
336
|
|
337
|
def __Node_clear(self):
|
338
|
while not is_empty(self): self.pop()
|
339
|
minidom.Node.clear = __Node_clear
|
340
|
|
341
|
#### Text
|
342
|
|
343
|
__Text_writexml_orig = minidom.Text.writexml
|
344
|
def __Text_writexml(self, *args, **kw_args):
|
345
|
if is_whitespace(self): pass # we add our own whitespace
|
346
|
else: __Text_writexml_orig(self, *args, **kw_args)
|
347
|
minidom.Text.writexml = __Text_writexml
|
348
|
|
349
|
#### Attr
|
350
|
|
351
|
def __Attr_str(self): return escape(self.name)+'="'+escape(self.value)+'"'
|
352
|
minidom.Attr.__str__ = __Attr_str
|
353
|
minidom.Attr.__repr__ = __Attr_str
|
354
|
|
355
|
#### Element
|
356
|
|
357
|
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
|
358
|
writer.write(indent+'<'+escape(self.tagName))
|
359
|
for attr_idx in xrange(self.attributes.length):
|
360
|
writer.write(' '+str(self.attributes.item(attr_idx)))
|
361
|
writer.write('>'+newl)
|
362
|
minidom.Element.write_opening = __Element_write_opening
|
363
|
|
364
|
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
|
365
|
writer.write('</'+escape(self.tagName)+'>'+newl)
|
366
|
minidom.Element.write_closing = __Element_write_closing
|
367
|
|
368
|
__Element_writexml_orig = minidom.Element.writexml
|
369
|
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
|
370
|
if isinstance(indent, int): indent = addindent*indent
|
371
|
if is_simple(self):
|
372
|
writer.write(indent)
|
373
|
__Element_writexml_orig(self, writer)
|
374
|
writer.write(newl)
|
375
|
else: __Element_writexml_orig(self, writer, indent, addindent, newl)
|
376
|
minidom.Element.writexml = __Element_writexml
|
377
|
|
378
|
#### Document
|
379
|
|
380
|
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
|
381
|
encoding=None):
|
382
|
xmlDecl = '<?xml version="1.0" '
|
383
|
if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
|
384
|
xmlDecl += '?>'+newl
|
385
|
writer.write(xmlDecl)
|
386
|
assert has_one_child(self)
|
387
|
assert is_elem(self.firstChild)
|
388
|
self.firstChild.write_opening(writer, indent, addindent, newl)
|
389
|
minidom.Document.write_opening = __Document_write_opening
|
390
|
|
391
|
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
|
392
|
self.firstChild.write_closing(writer, indent, addindent, newl)
|
393
|
minidom.Document.write_closing = __Document_write_closing
|