Project

General

Profile

1
# XML DOM tree manipulation
2

    
3
import cgi
4
from HTMLParser import HTMLParser
5
import itertools
6
import re
7
from xml.dom import Node
8
import xml.dom.minidom as minidom
9

    
10
import strings
11
import util
12

    
13
##### Escaping input
14

    
15
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
##### Names
22

    
23
def strip_namespace(name):
24
    namespace, sep, base = name.partition(':')
25
    if sep != '': return base
26
    else: return name
27

    
28
##### Nodes
29

    
30
def is_node(value): return isinstance(value, Node)
31

    
32
##### Replacing a node
33

    
34
def remove(node): node.parentNode.removeChild(node)
35

    
36
def replace(old, new):
37
    '''@param new Node|None'''
38
    assert old.parentNode != None # not removed from parent tree
39
    
40
    if new == None: old.parentNode.removeChild(old)
41
    else: old.parentNode.replaceChild(new, old) # note order reversed
42

    
43
def bool2str(val):
44
    '''For use with replace_with_text()'''
45
    if val: return '1'
46
    else: return None # remove node
47

    
48
def replace_with_text(node, new):
49
    '''
50
    @return The *new* node
51
    '''
52
    if isinstance(new, bool): new = bool2str(new)
53
    if util.is_str(new): new = node.ownerDocument.createTextNode(new)
54
    replace(node, new)
55
    return new
56

    
57
##### Element node contents
58

    
59
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
60

    
61
def is_completely_empty(node): return node.firstChild == None
62

    
63
def has_one_child(node):
64
    return node.firstChild != None and node.firstChild.nextSibling == None
65

    
66
def is_simple(node):
67
    '''Whether every child recursively has no more than one child'''
68
    return (not is_elem(node) or is_completely_empty(node)
69
        or (has_one_child(node) and is_simple(node.firstChild)))
70

    
71
class NodeIter:
72
    def __init__(self, node): self.child = node.firstChild
73
    
74
    def __iter__(self): return self
75
    
76
    def curr(self):
77
        if self.child != None: return self.child
78
        raise StopIteration
79
    
80
    def next(self):
81
        child = self.curr()
82
        self.child = self.child.nextSibling
83
        return child
84

    
85
##### Comments
86

    
87
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
88

    
89
def is_empty(node):
90
    for child in NodeIter(node):
91
        if not (is_whitespace(child) or is_comment(child)): return False
92
    return True
93

    
94
def clean_comment(str_):
95
    '''Sanitizes comment node contents. Strips invalid strings.'''
96
    return re.sub(r'-{2,}', r'-', str_) # comments can't contain '--'
97

    
98
def mk_comment(doc, str_): return doc.createComment(clean_comment(str_))
99

    
100
##### Child nodes that are elements
101

    
102
class NodeElemIter:
103
    def __init__(self, node): self.child = node.firstChild
104
    
105
    def __iter__(self): return self
106
    
107
    def curr(self):
108
        while self.child != None:
109
            if is_elem(self.child): return self.child
110
            self.child = self.child.nextSibling
111
        raise StopIteration
112
    
113
    def next(self):
114
        child = self.curr()
115
        self.child = self.child.nextSibling
116
        return child
117

    
118
def first_elem(node): return NodeElemIter(node).next()
119

    
120
def has_elems(node):
121
    try: first_elem(node); return True
122
    except StopIteration: return False
123

    
124
class NodeElemReverseIter:
125
    def __init__(self, node): self.child = node.lastChild
126
    
127
    def __iter__(self): return self
128
    
129
    def curr(self):
130
        while self.child != None:
131
            if is_elem(self.child): return self.child
132
            self.child = self.child.previousSibling
133
        raise StopIteration
134
    
135
    def next(self):
136
        child = self.curr()
137
        self.child = self.child.previousSibling
138
        return child
139

    
140
def last_elem(node): return NodeElemReverseIter(node).next()
141

    
142
class NodeEntryIter:
143
    def __init__(self, node): self.iter_ = NodeElemIter(node)
144
    
145
    def __iter__(self): return self
146
    
147
    def next(self):
148
        entry = self.iter_.next()
149
        if is_empty(entry): value = None
150
        else:
151
            assert has_one_child(entry) # TODO: convert to an exception
152
            value = entry.firstChild
153
        return (entry.tagName, value)
154

    
155
##### Parent nodes
156

    
157
def parent(node):
158
    '''Does not treat the document object as the root node's parent, since it's
159
    not a true element node'''
160
    parent_ = node.parentNode
161
    if parent_ != None and is_elem(parent_): return parent_
162
    else: return None
163

    
164
class NodeParentIter:
165
    '''See parent() for special treatment of root node.
166
    Note that the first element returned is the current node, not its parent.'''
167
    def __init__(self, node): self.node = node
168
    
169
    def __iter__(self): return self
170
    
171
    def curr(self):
172
        if self.node != None: return self.node
173
        else: raise StopIteration
174
    
175
    def next(self):
176
        node = self.curr()
177
        self.node = parent(self.node)
178
        return node
179

    
180
##### Element nodes containing text
181

    
182
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
183

    
184
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
185

    
186
def value_node(node):
187
    if is_elem(node):
188
        iter_ = NodeIter(node)
189
        util.skip(iter_, is_comment)
190
        try: return iter_.next()
191
        except StopIteration: return None
192
    else: return node
193

    
194
def value(node):
195
    value_ = util.do_ignore_none(lambda n: n.nodeValue, value_node(node))
196
    if value_ == strings.isspace_none_str: value_ = None # None equiv
197
    return value_
198

    
199
def is_whitespace(node):
200
    return is_text_node(node) and (node.nodeValue == ''
201
        or node.nodeValue.isspace())
202

    
203
def set_value(node, value):
204
    value_node_ = value_node(node)
205
    if value != None:
206
        if value_node_ != None:
207
            value_node_.nodeValue = value
208
        else:
209
            assert is_elem(node)
210
            node.appendChild(node.ownerDocument.createTextNode(value))
211
    elif value_node_ != None:
212
        if is_elem(node): remove(value_node_)
213
        else:
214
            if is_text_node(node): value = strings.isspace_none_str # None equiv
215
            node.nodeValue = value
216

    
217
class NodeTextEntryIter:
218
    def __init__(self, node): self.iter_ = NodeElemIter(node)
219
    
220
    def __iter__(self): return self
221
    
222
    def next(self):
223
        entry = self.iter_.next()
224
        if is_empty(entry): value_ = None
225
        elif is_text(entry): value_ = value(entry)
226
        else:
227
            assert has_one_child(entry) # TODO: convert to an exception
228
            value_ = entry.firstChild
229
        return (entry.tagName, value_)
230

    
231
def is_text_node_entry(val): return util.is_str(val[1])
232

    
233
def non_empty(iterable):
234
    return itertools.ifilter(lambda i: i[1] != None, iterable)
235

    
236
class TextEntryOnlyIter(util.CheckedIter):
237
    def __init__(self, iterable):
238
        util.CheckedIter.__init__(self, is_text_node_entry, non_empty(iterable))
239

    
240
##### IDs
241

    
242
def get_id(node):
243
    '''If the node doesn't have an ID, assumes the node itself is the ID.
244
    @return None if the node doesn't have an ID or a value
245
    '''
246
    id_ = node.getAttribute('id')
247
    if id_ != '': return id_
248
    else: return value(node) # assume the node itself is the ID
249

    
250
def set_id(node, id_): node.setAttribute('id', id_)
251

    
252
##### Child nodes
253

    
254
def set_child(node, name, value):
255
    '''Note: does not remove any existing child of the same name'''
256
    child = node.ownerDocument.createElement(name)
257
    set_value(child, value)
258
    node.appendChild(child)
259

    
260
def by_tag_name(node, name, last_only=False, ignore_namespace=False):
261
    '''last_only optimization returns only the last matching node'''
262
    if ignore_namespace: filter_name = strip_namespace
263
    else: filter_name = lambda name: name
264
    name = filter_name(name)
265
    
266
    children = []
267
    if last_only: iter_ = NodeElemReverseIter(node)
268
    else: iter_ = NodeElemIter(node)
269
    for child in iter_:
270
        if filter_name(child.tagName) == name:
271
            children.append(child)
272
            if last_only: break
273
    return children
274

    
275
def merge(from_, into):
276
    '''Merges two nodes of the same tag name and their newly-adjacent children.
277
    @post The into node is saved; the from_ node is deleted.
278
    '''
279
    if from_ == None or into == None: return # base case
280
    if from_.tagName != into.tagName: return # not mergeable
281
    
282
    from_first = from_.firstChild # save before merge
283
    for child in NodeIter(from_): into.appendChild(child)
284
    remove(from_)
285
    
286
    # Recurse
287
    merge(from_first, from_first.previousSibling) # = into.lastChild
288

    
289
def merge_by_name(root, name):
290
    '''Merges siblings in root with the given name'''
291
    children = by_tag_name(root, name)
292
    child0 = children.pop(0)
293
    for child in children: merge(child, child0)
294

    
295
##### XML documents
296

    
297
def create_doc(root='_'):
298
    return minidom.getDOMImplementation().createDocument(None, root, None)
299

    
300
##### Printing XML
301

    
302
prettyxml_config = dict(addindent='    ', newl='\n')
303
toprettyxml_config = prettyxml_config.copy()
304
util.rename_key(toprettyxml_config, 'addindent', 'indent')
305

    
306
##### minidom modifications
307

    
308
#### Module
309

    
310
minidom._write_data = lambda writer, data: writer.write(escape(data))
311

    
312
minidom.Node.__iter__ = lambda self: NodeIter(self)
313

    
314
def __Node_str(self):
315
    return strings.remove_extra_newl(self.toprettyxml(**toprettyxml_config))
316
minidom.Node.__str__ = __Node_str
317
minidom.Node.__repr__ = __Node_str
318
minidom.Element.__repr__ = __Node_str
319

    
320
#### Node
321

    
322
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
323

    
324
def __Node_clear(self):
325
    while not is_empty(self): self.pop()
326
minidom.Node.clear = __Node_clear
327

    
328
#### Text
329

    
330
__Text_writexml_orig = minidom.Text.writexml
331
def __Text_writexml(self, *args, **kw_args):
332
    if is_whitespace(self): pass # we add our own whitespace
333
    else: __Text_writexml_orig(self, *args, **kw_args)
334
minidom.Text.writexml = __Text_writexml
335

    
336
#### Attr
337

    
338
def __Attr_str(self): return escape(self.name)+'="'+escape(self.value)+'"'
339
minidom.Attr.__str__ = __Attr_str
340
minidom.Attr.__repr__ = __Attr_str
341

    
342
#### Element
343

    
344
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
345
    writer.write(indent+'<'+escape(self.tagName))
346
    for attr_idx in xrange(self.attributes.length):
347
        writer.write(' '+str(self.attributes.item(attr_idx)))
348
    writer.write('>'+newl)
349
minidom.Element.write_opening = __Element_write_opening
350

    
351
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
352
    writer.write('</'+escape(self.tagName)+'>'+newl)
353
minidom.Element.write_closing = __Element_write_closing
354

    
355
__Element_writexml_orig = minidom.Element.writexml
356
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
357
    if isinstance(indent, int): indent = addindent*indent
358
    if is_simple(self):
359
        writer.write(indent)
360
        __Element_writexml_orig(self, writer)
361
        writer.write(newl)
362
    else: __Element_writexml_orig(self, writer, indent, addindent, newl)
363
minidom.Element.writexml = __Element_writexml
364

    
365
#### Document
366

    
367
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
368
    encoding=None):
369
    xmlDecl = '<?xml version="1.0" '
370
    if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
371
    xmlDecl += '?>'+newl
372
    writer.write(xmlDecl)
373
    assert has_one_child(self)
374
    assert is_elem(self.firstChild)
375
    self.firstChild.write_opening(writer, indent, addindent, newl)
376
minidom.Document.write_opening = __Document_write_opening
377

    
378
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
379
    self.firstChild.write_closing(writer, indent, addindent, newl)
380
minidom.Document.write_closing = __Document_write_closing
(36-36/40)