1
|
# XML DOM tree manipulation
|
2
|
|
3
|
import cgi
|
4
|
from HTMLParser import HTMLParser
|
5
|
import re
|
6
|
from xml.dom import Node
|
7
|
import xml.dom.minidom as minidom
|
8
|
|
9
|
import strings
|
10
|
import util
|
11
|
|
12
|
##### Escaping input
|
13
|
|
14
|
def escape(str_):
|
15
|
return strings.to_unicode(cgi.escape(str_, True)).encode('ascii',
|
16
|
'xmlcharrefreplace')
|
17
|
|
18
|
def unescape(str_): return HTMLParser().unescape(str_)
|
19
|
|
20
|
##### Names
|
21
|
|
22
|
def strip_namespace(name):
|
23
|
namespace, sep, base = name.partition(':')
|
24
|
if sep != '': return base
|
25
|
else: return name
|
26
|
|
27
|
##### IDs
|
28
|
|
29
|
def get_id(node): return node.getAttribute('id')
|
30
|
|
31
|
def set_id(node, id_): node.setAttribute('id', id_)
|
32
|
|
33
|
##### Element node contents
|
34
|
|
35
|
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
|
36
|
|
37
|
def is_completely_empty(node): return node.firstChild == None
|
38
|
|
39
|
def has_one_child(node):
|
40
|
return node.firstChild != None and node.firstChild.nextSibling == None
|
41
|
|
42
|
def is_simple(node):
|
43
|
'''Whether every child recursively has no more than one child'''
|
44
|
return (not is_elem(node) or is_completely_empty(node)
|
45
|
or (has_one_child(node) and is_simple(node.firstChild)))
|
46
|
|
47
|
class NodeIter:
|
48
|
def __init__(self, node): self.child = node.firstChild
|
49
|
|
50
|
def __iter__(self): return self
|
51
|
|
52
|
def curr(self):
|
53
|
if self.child != None: return self.child
|
54
|
raise StopIteration
|
55
|
|
56
|
def next(self):
|
57
|
child = self.curr()
|
58
|
self.child = self.child.nextSibling
|
59
|
return child
|
60
|
|
61
|
##### Comments
|
62
|
|
63
|
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
|
64
|
|
65
|
def is_empty(node):
|
66
|
for child in NodeIter(node):
|
67
|
if not is_comment(child): return False
|
68
|
return True
|
69
|
|
70
|
def clean_comment(str_):
|
71
|
'''Sanitizes comment node contents. Strips invalid strings.'''
|
72
|
return re.sub(r'-{2,}', r'-', str_) # comments can't contain '--'
|
73
|
|
74
|
def mk_comment(doc, str_): return doc.createComment(clean_comment(str_))
|
75
|
|
76
|
##### Child nodes that are elements
|
77
|
|
78
|
class NodeElemIter:
|
79
|
def __init__(self, node): self.child = node.firstChild
|
80
|
|
81
|
def __iter__(self): return self
|
82
|
|
83
|
def curr(self):
|
84
|
while self.child != None:
|
85
|
if is_elem(self.child): return self.child
|
86
|
self.child = self.child.nextSibling
|
87
|
raise StopIteration
|
88
|
|
89
|
def next(self):
|
90
|
child = self.curr()
|
91
|
self.child = self.child.nextSibling
|
92
|
return child
|
93
|
|
94
|
def first_elem(node): return NodeElemIter(node).next()
|
95
|
|
96
|
def has_elems(node):
|
97
|
try: first_elem(node); return True
|
98
|
except StopIteration: return False
|
99
|
|
100
|
class NodeElemReverseIter:
|
101
|
def __init__(self, node): self.child = node.lastChild
|
102
|
|
103
|
def __iter__(self): return self
|
104
|
|
105
|
def curr(self):
|
106
|
while self.child != None:
|
107
|
if is_elem(self.child): return self.child
|
108
|
self.child = self.child.previousSibling
|
109
|
raise StopIteration
|
110
|
|
111
|
def next(self):
|
112
|
child = self.curr()
|
113
|
self.child = self.child.previousSibling
|
114
|
return child
|
115
|
|
116
|
def last_elem(node): return NodeElemReverseIter(node).next()
|
117
|
|
118
|
##### Parent nodes
|
119
|
|
120
|
def parent(node):
|
121
|
'''Does not treat the document object as the root node's parent, since it's
|
122
|
not a true element node'''
|
123
|
parent_ = node.parentNode
|
124
|
if parent_ != None and is_elem(parent_): return parent_
|
125
|
else: return None
|
126
|
|
127
|
class NodeParentIter:
|
128
|
'''See parent() for special treatment of root node.
|
129
|
Note that the first element returned is the current node, not its parent.'''
|
130
|
def __init__(self, node): self.node = node
|
131
|
|
132
|
def __iter__(self): return self
|
133
|
|
134
|
def curr(self):
|
135
|
if self.node != None: return self.node
|
136
|
else: raise StopIteration
|
137
|
|
138
|
def next(self):
|
139
|
node = self.curr()
|
140
|
self.node = parent(self.node)
|
141
|
return node
|
142
|
|
143
|
##### Element nodes containing text
|
144
|
|
145
|
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
|
146
|
|
147
|
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
|
148
|
|
149
|
def value(node):
|
150
|
if node.firstChild != None: return node.firstChild.nodeValue
|
151
|
else: return node.nodeValue
|
152
|
|
153
|
def is_whitespace(node): return is_text_node(node) and value(node).isspace()
|
154
|
|
155
|
def set_value(node, value):
|
156
|
if is_elem(node): node.appendChild(node.ownerDocument.createTextNode(value))
|
157
|
else: node.nodeValue = value
|
158
|
|
159
|
class NodeTextEntryIter:
|
160
|
def __init__(self, node): self.iter_ = NodeElemIter(node)
|
161
|
|
162
|
def __iter__(self): return self
|
163
|
|
164
|
def next(self):
|
165
|
util.skip(self.iter_, is_empty)
|
166
|
entry = self.iter_.next()
|
167
|
if is_text(entry): value_ = value(entry)
|
168
|
else:
|
169
|
assert has_one_child(entry) # TODO: convert to an exception
|
170
|
value_ = entry.firstChild
|
171
|
return (entry.tagName, value_)
|
172
|
|
173
|
def is_text_node_entry(val): return util.is_str(val[1])
|
174
|
|
175
|
class TextEntryOnlyIter(util.CheckedIter):
|
176
|
def __init__(self, iterable):
|
177
|
util.CheckedIter.__init__(self, is_text_node_entry, iterable)
|
178
|
|
179
|
##### Modifying/replacing a node
|
180
|
|
181
|
def set_child(node, name, value):
|
182
|
'''Note: does not remove any existing child of the same name'''
|
183
|
child = node.ownerDocument.createElement(name)
|
184
|
set_value(child, value)
|
185
|
node.appendChild(child)
|
186
|
|
187
|
def remove(node): node.parentNode.removeChild(node)
|
188
|
|
189
|
def replace(old, new):
|
190
|
'''@param new Node|None'''
|
191
|
if new == None: old.parentNode.removeChild(old)
|
192
|
else: old.parentNode.replaceChild(new, old) # note order reversed
|
193
|
|
194
|
def replace_with_text(node, new):
|
195
|
if util.is_str(new): new = node.ownerDocument.createTextNode(new)
|
196
|
replace(node, new)
|
197
|
|
198
|
##### Searching child nodes
|
199
|
|
200
|
def by_tag_name(node, name, last_only=False, ignore_namespace=False):
|
201
|
'''last_only optimization returns only the last matching node'''
|
202
|
if ignore_namespace: filter_name = strip_namespace
|
203
|
else: filter_name = lambda name: name
|
204
|
name = filter_name(name)
|
205
|
|
206
|
children = []
|
207
|
if last_only: iter_ = NodeElemReverseIter(node)
|
208
|
else: iter_ = NodeElemIter(node)
|
209
|
for child in iter_:
|
210
|
if filter_name(child.tagName) == name:
|
211
|
children.append(child)
|
212
|
if last_only: break
|
213
|
return children
|
214
|
|
215
|
##### XML documents
|
216
|
|
217
|
def create_doc(root='_'):
|
218
|
return minidom.getDOMImplementation().createDocument(None, root, None)
|
219
|
|
220
|
##### Printing XML
|
221
|
|
222
|
prettyxml_config = dict(addindent=' ', newl='\n')
|
223
|
toprettyxml_config = prettyxml_config.copy()
|
224
|
util.rename_key(toprettyxml_config, 'addindent', 'indent')
|
225
|
|
226
|
##### minidom modifications
|
227
|
|
228
|
#### Module
|
229
|
|
230
|
minidom._write_data = lambda writer, data: writer.write(escape(data))
|
231
|
|
232
|
minidom.Node.__iter__ = lambda self: NodeIter(self)
|
233
|
|
234
|
def __Node_str(self):
|
235
|
return strings.remove_extra_newl(self.toprettyxml(**toprettyxml_config))
|
236
|
minidom.Node.__str__ = __Node_str
|
237
|
minidom.Node.__repr__ = __Node_str
|
238
|
minidom.Element.__repr__ = __Node_str
|
239
|
|
240
|
#### Node
|
241
|
|
242
|
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
|
243
|
|
244
|
def __Node_clear(self):
|
245
|
while not is_empty(self): self.pop()
|
246
|
minidom.Node.clear = __Node_clear
|
247
|
|
248
|
#### Text
|
249
|
|
250
|
__Text_writexml_orig = minidom.Text.writexml
|
251
|
def __Text_writexml(self, *args, **kw_args):
|
252
|
if is_whitespace(self): pass # we add our own whitespace
|
253
|
else: __Text_writexml_orig(self, *args, **kw_args)
|
254
|
minidom.Text.writexml = __Text_writexml
|
255
|
|
256
|
#### Attr
|
257
|
|
258
|
def __Attr_str(self): return escape(self.name)+'="'+escape(self.value)+'"'
|
259
|
minidom.Attr.__str__ = __Attr_str
|
260
|
minidom.Attr.__repr__ = __Attr_str
|
261
|
|
262
|
#### Element
|
263
|
|
264
|
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
|
265
|
writer.write(indent+'<'+escape(self.tagName))
|
266
|
for attr_idx in xrange(self.attributes.length):
|
267
|
writer.write(' '+str(self.attributes.item(attr_idx)))
|
268
|
writer.write('>'+newl)
|
269
|
minidom.Element.write_opening = __Element_write_opening
|
270
|
|
271
|
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
|
272
|
writer.write('</'+escape(self.tagName)+'>'+newl)
|
273
|
minidom.Element.write_closing = __Element_write_closing
|
274
|
|
275
|
__Element_writexml_orig = minidom.Element.writexml
|
276
|
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
|
277
|
if isinstance(indent, int): indent = addindent*indent
|
278
|
if is_simple(self):
|
279
|
writer.write(indent)
|
280
|
__Element_writexml_orig(self, writer)
|
281
|
writer.write(newl)
|
282
|
else: __Element_writexml_orig(self, writer, indent, addindent, newl)
|
283
|
minidom.Element.writexml = __Element_writexml
|
284
|
|
285
|
#### Document
|
286
|
|
287
|
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
|
288
|
encoding=None):
|
289
|
xmlDecl = '<?xml version="1.0" '
|
290
|
if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
|
291
|
xmlDecl += '?>'+newl
|
292
|
writer.write(xmlDecl)
|
293
|
assert has_one_child(self)
|
294
|
assert is_elem(self.firstChild)
|
295
|
self.firstChild.write_opening(writer, indent, addindent, newl)
|
296
|
minidom.Document.write_opening = __Document_write_opening
|
297
|
|
298
|
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
|
299
|
self.firstChild.write_closing(writer, indent, addindent, newl)
|
300
|
minidom.Document.write_closing = __Document_write_closing
|