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 replace_with_text(node, new):
44
    '''
45
    @return The *new* node
46
    '''
47
    if isinstance(new, bool): new = util.bool2str(new)
48
    if util.is_str(new): new = node.ownerDocument.createTextNode(new)
49
    replace(node, new)
50
    return new
51

    
52
##### Element node contents
53

    
54
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
55

    
56
def is_completely_empty(node): return node.firstChild == None
57

    
58
def has_one_child(node):
59
    return node.firstChild != None and node.firstChild.nextSibling == None
60

    
61
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
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
##### Comments
81

    
82
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
83

    
84
def is_empty(node):
85
    for child in NodeIter(node):
86
        if not (is_whitespace(child) or is_comment(child)): return False
87
    return True
88

    
89
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
##### Child nodes that are elements
96

    
97
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
            if is_elem(self.child): return self.child
105
            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
def has_elems(node):
116
    try: first_elem(node); return True
117
    except StopIteration: return False
118

    
119
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
            if is_elem(self.child): return self.child
127
            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
##### Parent nodes
138

    
139
def parent(node):
140
    '''Does not treat the document object as the root node's parent, since it's
141
    not a true element node'''
142
    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
    def __init__(self, node): self.node = node
150
    
151
    def __iter__(self): return self
152
    
153
    def curr(self):
154
        if self.node != None: return self.node
155
        else: raise StopIteration
156
    
157
    def next(self):
158
        node = self.curr()
159
        self.node = parent(self.node)
160
        return node
161

    
162
##### Element nodes containing text
163

    
164
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
165

    
166
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
167

    
168
def value_node(node):
169
    if is_elem(node):
170
        iter_ = NodeIter(node)
171
        util.skip(iter_, is_comment)
172
        try: return iter_.next()
173
        except StopIteration: return None
174
    else: return node
175

    
176
def value(node):
177
    value_ = util.do_ignore_none(lambda n: n.nodeValue, value_node(node))
178
    if value_ == strings.isspace_none_str: value_ = None # None equiv
179
    return value_
180

    
181
def is_whitespace(node):
182
    return is_text_node(node) and (node.nodeValue == ''
183
        or node.nodeValue.isspace())
184

    
185
def set_value(node, value):
186
    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
    elif value_node_ != None:
194
        if is_elem(node): remove(value_node_)
195
        else:
196
            if is_text_node(node): value = strings.isspace_none_str # None equiv
197
            node.nodeValue = value
198

    
199
class NodeTextEntryIter:
200
    def __init__(self, node): self.iter_ = NodeElemIter(node)
201
    
202
    def __iter__(self): return self
203
    
204
    def next(self):
205
        entry = self.iter_.next()
206
        if is_empty(entry): value_ = None
207
        elif is_text(entry): value_ = value(entry)
208
        else:
209
            assert has_one_child(entry) # TODO: convert to an exception
210
            value_ = entry.firstChild
211
        return (entry.tagName, value_)
212

    
213
def is_text_node_entry(val): return util.is_str(val[1])
214

    
215
def non_empty(iterable):
216
    return itertools.ifilter(lambda i: i[1] != None, iterable)
217

    
218
class TextEntryOnlyIter(util.CheckedIter):
219
    def __init__(self, iterable):
220
        util.CheckedIter.__init__(self, is_text_node_entry, non_empty(iterable))
221

    
222
##### 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
##### Child nodes
235

    
236
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
    set_value(child, value)
240
    node.appendChild(child)
241

    
242
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
    children = []
249
    if last_only: iter_ = NodeElemReverseIter(node)
250
    else: iter_ = NodeElemIter(node)
251
    for child in iter_:
252
        if filter_name(child.tagName) == name:
253
            children.append(child)
254
            if last_only: break
255
    return children
256

    
257
def merge(from_, into):
258
    '''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
    for child in NodeIter(from_): into.appendChild(child)
266
    remove(from_)
267
    
268
    # Recurse
269
    merge(from_first, from_first.previousSibling) # = into.lastChild
270

    
271
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
##### XML documents
278

    
279
def create_doc(root='_'):
280
    return minidom.getDOMImplementation().createDocument(None, root, None)
281

    
282
##### Printing XML
283

    
284
prettyxml_config = dict(addindent='    ', newl='\n')
285
toprettyxml_config = prettyxml_config.copy()
286
util.rename_key(toprettyxml_config, 'addindent', 'indent')
287

    
288
##### minidom modifications
289

    
290
#### Module
291

    
292
minidom._write_data = lambda writer, data: writer.write(escape(data))
293

    
294
minidom.Node.__iter__ = lambda self: NodeIter(self)
295

    
296
def __Node_str(self):
297
    return strings.remove_extra_newl(self.toprettyxml(**toprettyxml_config))
298
minidom.Node.__str__ = __Node_str
299
minidom.Node.__repr__ = __Node_str
300
minidom.Element.__repr__ = __Node_str
301

    
302
#### Node
303

    
304
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
#### 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
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
327
    writer.write(indent+'<'+escape(self.tagName))
328
    for attr_idx in xrange(self.attributes.length):
329
        writer.write(' '+str(self.attributes.item(attr_idx)))
330
    writer.write('>'+newl)
331
minidom.Element.write_opening = __Element_write_opening
332

    
333
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
334
    writer.write('</'+escape(self.tagName)+'>'+newl)
335
minidom.Element.write_closing = __Element_write_closing
336

    
337
__Element_writexml_orig = minidom.Element.writexml
338
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
339
    if isinstance(indent, int): indent = addindent*indent
340
    if is_simple(self):
341
        writer.write(indent)
342
        __Element_writexml_orig(self, writer)
343
        writer.write(newl)
344
    else: __Element_writexml_orig(self, writer, indent, addindent, newl)
345
minidom.Element.writexml = __Element_writexml
346

    
347
#### Document
348

    
349
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
(36-36/40)