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