Project

General

Profile

1
# XML DOM tree manipulation
2

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

    
9
import strings
10
import util
11

    
12
##### Escaping input
13

    
14
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
##### Names
21

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

    
27
##### Nodes
28

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

    
31
##### 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
    '''
42
    @return The *new* node
43
    '''
44
    if util.is_str(new): new = node.ownerDocument.createTextNode(new)
45
    replace(node, new)
46
    return new
47

    
48
##### Element node contents
49

    
50
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
51

    
52
def is_completely_empty(node): return node.firstChild == None
53

    
54
def has_one_child(node):
55
    return node.firstChild != None and node.firstChild.nextSibling == None
56

    
57
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
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
##### Comments
77

    
78
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
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
##### Child nodes that are elements
92

    
93
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
            if is_elem(self.child): return self.child
101
            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
def has_elems(node):
112
    try: first_elem(node); return True
113
    except StopIteration: return False
114

    
115
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
            if is_elem(self.child): return self.child
123
            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
##### Parent nodes
134

    
135
def parent(node):
136
    '''Does not treat the document object as the root node's parent, since it's
137
    not a true element node'''
138
    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
    def __init__(self, node): self.node = node
146
    
147
    def __iter__(self): return self
148
    
149
    def curr(self):
150
        if self.node != None: return self.node
151
        else: raise StopIteration
152
    
153
    def next(self):
154
        node = self.curr()
155
        self.node = parent(self.node)
156
        return node
157

    
158
##### Element nodes containing text
159

    
160
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
161

    
162
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
163

    
164
def value_node(node):
165
    if is_elem(node):
166
        iter_ = NodeIter(node)
167
        util.skip(iter_, is_comment)
168
        try: return iter_.next()
169
        except StopIteration: return None
170
    else: return node
171

    
172
def value(node):
173
    return util.do_ignore_none(lambda n: n.nodeValue, value_node(node))
174

    
175
def is_whitespace(node): return is_text_node(node) and value(node).isspace()
176

    
177
def set_value(node, value):
178
    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
    elif value_node_ != None:
186
        if is_elem(node): remove(value_node_)
187
        else: node.nodeValue = value
188

    
189
class NodeTextEntryIter:
190
    def __init__(self, node): self.iter_ = NodeElemIter(node)
191
    
192
    def __iter__(self): return self
193
    
194
    def next(self):
195
        util.skip(self.iter_, is_empty)
196
        entry = self.iter_.next()
197
        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

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

    
223
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
    set_value(child, value)
227
    node.appendChild(child)
228

    
229
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
    children = []
236
    if last_only: iter_ = NodeElemReverseIter(node)
237
    else: iter_ = NodeElemIter(node)
238
    for child in iter_:
239
        if filter_name(child.tagName) == name:
240
            children.append(child)
241
            if last_only: break
242
    return children
243

    
244
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 a node with its siblings as long as they or their
251
    newly-adjacent 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
def merge_same_name(node):
261
    '''Merges nodes with the same name as a node, using merge_adjacent()'''
262
    for node_ in by_tag_name(node.parentNode, node.tagName):
263
        if node_ is node: continue # not self
264
        merge_adjacent(node_)
265

    
266
##### XML documents
267

    
268
def create_doc(root='_'):
269
    return minidom.getDOMImplementation().createDocument(None, root, None)
270

    
271
##### Printing XML
272

    
273
prettyxml_config = dict(addindent='    ', newl='\n')
274
toprettyxml_config = prettyxml_config.copy()
275
util.rename_key(toprettyxml_config, 'addindent', 'indent')
276

    
277
##### minidom modifications
278

    
279
#### Module
280

    
281
minidom._write_data = lambda writer, data: writer.write(escape(data))
282

    
283
minidom.Node.__iter__ = lambda self: NodeIter(self)
284

    
285
def __Node_str(self):
286
    return strings.remove_extra_newl(self.toprettyxml(**toprettyxml_config))
287
minidom.Node.__str__ = __Node_str
288
minidom.Node.__repr__ = __Node_str
289
minidom.Element.__repr__ = __Node_str
290

    
291
#### Node
292

    
293
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
294

    
295
def __Node_clear(self):
296
    while not is_empty(self): self.pop()
297
minidom.Node.clear = __Node_clear
298

    
299
#### Text
300

    
301
__Text_writexml_orig = minidom.Text.writexml
302
def __Text_writexml(self, *args, **kw_args):
303
    if is_whitespace(self): pass # we add our own whitespace
304
    else: __Text_writexml_orig(self, *args, **kw_args)
305
minidom.Text.writexml = __Text_writexml
306

    
307
#### Attr
308

    
309
def __Attr_str(self): return escape(self.name)+'="'+escape(self.value)+'"'
310
minidom.Attr.__str__ = __Attr_str
311
minidom.Attr.__repr__ = __Attr_str
312

    
313
#### Element
314

    
315
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
316
    writer.write(indent+'<'+escape(self.tagName))
317
    for attr_idx in xrange(self.attributes.length):
318
        writer.write(' '+str(self.attributes.item(attr_idx)))
319
    writer.write('>'+newl)
320
minidom.Element.write_opening = __Element_write_opening
321

    
322
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
323
    writer.write('</'+escape(self.tagName)+'>'+newl)
324
minidom.Element.write_closing = __Element_write_closing
325

    
326
__Element_writexml_orig = minidom.Element.writexml
327
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
328
    if isinstance(indent, int): indent = addindent*indent
329
    if is_simple(self):
330
        writer.write(indent)
331
        __Element_writexml_orig(self, writer)
332
        writer.write(newl)
333
    else: __Element_writexml_orig(self, writer, indent, addindent, newl)
334
minidom.Element.writexml = __Element_writexml
335

    
336
#### Document
337

    
338
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
339
    encoding=None):
340
    xmlDecl = '<?xml version="1.0" '
341
    if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
342
    xmlDecl += '?>'+newl
343
    writer.write(xmlDecl)
344
    assert has_one_child(self)
345
    assert is_elem(self.firstChild)
346
    self.firstChild.write_opening(writer, indent, addindent, newl)
347
minidom.Document.write_opening = __Document_write_opening
348

    
349
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
350
    self.firstChild.write_closing(writer, indent, addindent, newl)
351
minidom.Document.write_closing = __Document_write_closing
(33-33/37)