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
    assert old.parentNode != None # not removed from parent tree
38
    
39
    if new == None: old.parentNode.removeChild(old)
40
    else: old.parentNode.replaceChild(new, old) # note order reversed
41

    
42
def replace_with_text(node, new):
43
    '''
44
    @return The *new* node
45
    '''
46
    if util.is_str(new): new = node.ownerDocument.createTextNode(new)
47
    replace(node, new)
48
    return new
49

    
50
##### Element node contents
51

    
52
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
53

    
54
def is_completely_empty(node): return node.firstChild == None
55

    
56
def has_one_child(node):
57
    return node.firstChild != None and node.firstChild.nextSibling == None
58

    
59
def is_simple(node):
60
    '''Whether every child recursively has no more than one child'''
61
    return (not is_elem(node) or is_completely_empty(node)
62
        or (has_one_child(node) and is_simple(node.firstChild)))
63

    
64
class NodeIter:
65
    def __init__(self, node): self.child = node.firstChild
66
    
67
    def __iter__(self): return self
68
    
69
    def curr(self):
70
        if self.child != None: return self.child
71
        raise StopIteration
72
    
73
    def next(self):
74
        child = self.curr()
75
        self.child = self.child.nextSibling
76
        return child
77

    
78
##### Comments
79

    
80
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
81

    
82
def is_empty(node):
83
    for child in NodeIter(node):
84
        if not is_comment(child): return False
85
    return True
86

    
87
def clean_comment(str_):
88
    '''Sanitizes comment node contents. Strips invalid strings.'''
89
    return re.sub(r'-{2,}', r'-', str_) # comments can't contain '--'
90

    
91
def mk_comment(doc, str_): return doc.createComment(clean_comment(str_))
92

    
93
##### Child nodes that are elements
94

    
95
class NodeElemIter:
96
    def __init__(self, node): self.child = node.firstChild
97
    
98
    def __iter__(self): return self
99
    
100
    def curr(self):
101
        while self.child != None:
102
            if is_elem(self.child): return self.child
103
            self.child = self.child.nextSibling
104
        raise StopIteration
105
    
106
    def next(self):
107
        child = self.curr()
108
        self.child = self.child.nextSibling
109
        return child
110

    
111
def first_elem(node): return NodeElemIter(node).next()
112

    
113
def has_elems(node):
114
    try: first_elem(node); return True
115
    except StopIteration: return False
116

    
117
class NodeElemReverseIter:
118
    def __init__(self, node): self.child = node.lastChild
119
    
120
    def __iter__(self): return self
121
    
122
    def curr(self):
123
        while self.child != None:
124
            if is_elem(self.child): return self.child
125
            self.child = self.child.previousSibling
126
        raise StopIteration
127
    
128
    def next(self):
129
        child = self.curr()
130
        self.child = self.child.previousSibling
131
        return child
132

    
133
def last_elem(node): return NodeElemReverseIter(node).next()
134

    
135
##### Parent nodes
136

    
137
def parent(node):
138
    '''Does not treat the document object as the root node's parent, since it's
139
    not a true element node'''
140
    parent_ = node.parentNode
141
    if parent_ != None and is_elem(parent_): return parent_
142
    else: return None
143

    
144
class NodeParentIter:
145
    '''See parent() for special treatment of root node.
146
    Note that the first element returned is the current node, not its parent.'''
147
    def __init__(self, node): self.node = node
148
    
149
    def __iter__(self): return self
150
    
151
    def curr(self):
152
        if self.node != None: return self.node
153
        else: raise StopIteration
154
    
155
    def next(self):
156
        node = self.curr()
157
        self.node = parent(self.node)
158
        return node
159

    
160
##### Element nodes containing text
161

    
162
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
163

    
164
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
165

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

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

    
177
def is_whitespace(node): return is_text_node(node) and value(node).isspace()
178

    
179
def set_value(node, value):
180
    value_node_ = value_node(node)
181
    if value != None:
182
        if value_node_ != None:
183
            value_node_.nodeValue = value
184
        else:
185
            assert is_elem(node)
186
            node.appendChild(node.ownerDocument.createTextNode(value))
187
    elif value_node_ != None:
188
        if is_elem(node): remove(value_node_)
189
        else: node.nodeValue = value
190

    
191
class NodeTextEntryIter:
192
    def __init__(self, node): self.iter_ = NodeElemIter(node)
193
    
194
    def __iter__(self): return self
195
    
196
    def next(self):
197
        util.skip(self.iter_, is_empty)
198
        entry = self.iter_.next()
199
        if is_text(entry): value_ = value(entry)
200
        else:
201
            assert has_one_child(entry) # TODO: convert to an exception
202
            value_ = entry.firstChild
203
        return (entry.tagName, value_)
204

    
205
def is_text_node_entry(val): return util.is_str(val[1])
206

    
207
class TextEntryOnlyIter(util.CheckedIter):
208
    def __init__(self, iterable):
209
        util.CheckedIter.__init__(self, is_text_node_entry, iterable)
210

    
211
##### IDs
212

    
213
def get_id(node):
214
    '''If the node doesn't have an ID, assumes the node itself is the ID.
215
    @return None if the node doesn't have an ID or a value
216
    '''
217
    id_ = node.getAttribute('id')
218
    if id_ != '': return id_
219
    else: return value(node) # assume the node itself is the ID
220

    
221
def set_id(node, id_): node.setAttribute('id', id_)
222

    
223
##### Child nodes
224

    
225
def set_child(node, name, value):
226
    '''Note: does not remove any existing child of the same name'''
227
    child = node.ownerDocument.createElement(name)
228
    set_value(child, value)
229
    node.appendChild(child)
230

    
231
def by_tag_name(node, name, last_only=False, ignore_namespace=False):
232
    '''last_only optimization returns only the last matching node'''
233
    if ignore_namespace: filter_name = strip_namespace
234
    else: filter_name = lambda name: name
235
    name = filter_name(name)
236
    
237
    children = []
238
    if last_only: iter_ = NodeElemReverseIter(node)
239
    else: iter_ = NodeElemIter(node)
240
    for child in iter_:
241
        if filter_name(child.tagName) == name:
242
            children.append(child)
243
            if last_only: break
244
    return children
245

    
246
def merge(from_, into):
247
    '''Merges two nodes of the same tag name and their newly-adjacent children.
248
    @post The into node is saved; the from_ node is deleted.
249
    '''
250
    if from_ == None or into == None: return # base case
251
    if from_.tagName != into.tagName: return # not mergeable
252
    
253
    from_first = from_.firstChild # save before merge
254
    for child in NodeIter(from_): into.appendChild(child)
255
    remove(from_)
256
    
257
    # Recurse
258
    merge(from_first, from_first.previousSibling) # = into.lastChild
259

    
260
def merge_by_name(root, name):
261
    '''Merges siblings in root with the given name'''
262
    children = by_tag_name(root, name)
263
    child0 = children.pop(0)
264
    for child in children: merge(child, child0)
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)