Project

General

Profile

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