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