Project

General

Profile

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