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
##### Replacing a node
28

    
29
def remove(node): node.parentNode.removeChild(node)
30

    
31
def replace(old, new):
32
    '''@param new Node|None'''
33
    if new == None: old.parentNode.removeChild(old)
34
    else: old.parentNode.replaceChild(new, old) # note order reversed
35

    
36
def replace_with_text(node, new):
37
    if util.is_str(new): new = node.ownerDocument.createTextNode(new)
38
    replace(node, new)
39

    
40
##### Element node contents
41

    
42
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
43

    
44
def is_completely_empty(node): return node.firstChild == None
45

    
46
def has_one_child(node):
47
    return node.firstChild != None and node.firstChild.nextSibling == None
48

    
49
def is_simple(node):
50
    '''Whether every child recursively has no more than one child'''
51
    return (not is_elem(node) or is_completely_empty(node)
52
        or (has_one_child(node) and is_simple(node.firstChild)))
53

    
54
class NodeIter:
55
    def __init__(self, node): self.child = node.firstChild
56
    
57
    def __iter__(self): return self
58
    
59
    def curr(self):
60
        if self.child != None: return self.child
61
        raise StopIteration
62
    
63
    def next(self):
64
        child = self.curr()
65
        self.child = self.child.nextSibling
66
        return child
67

    
68
##### Comments
69

    
70
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
71

    
72
def is_empty(node):
73
    for child in NodeIter(node):
74
        if not is_comment(child): return False
75
    return True
76

    
77
def clean_comment(str_):
78
    '''Sanitizes comment node contents. Strips invalid strings.'''
79
    return re.sub(r'-{2,}', r'-', str_) # comments can't contain '--'
80

    
81
def mk_comment(doc, str_): return doc.createComment(clean_comment(str_))
82

    
83
##### Child nodes that are elements
84

    
85
class NodeElemIter:
86
    def __init__(self, node): self.child = node.firstChild
87
    
88
    def __iter__(self): return self
89
    
90
    def curr(self):
91
        while self.child != None:
92
            if is_elem(self.child): return self.child
93
            self.child = self.child.nextSibling
94
        raise StopIteration
95
    
96
    def next(self):
97
        child = self.curr()
98
        self.child = self.child.nextSibling
99
        return child
100

    
101
def first_elem(node): return NodeElemIter(node).next()
102

    
103
def has_elems(node):
104
    try: first_elem(node); return True
105
    except StopIteration: return False
106

    
107
class NodeElemReverseIter:
108
    def __init__(self, node): self.child = node.lastChild
109
    
110
    def __iter__(self): return self
111
    
112
    def curr(self):
113
        while self.child != None:
114
            if is_elem(self.child): return self.child
115
            self.child = self.child.previousSibling
116
        raise StopIteration
117
    
118
    def next(self):
119
        child = self.curr()
120
        self.child = self.child.previousSibling
121
        return child
122

    
123
def last_elem(node): return NodeElemReverseIter(node).next()
124

    
125
##### Parent nodes
126

    
127
def parent(node):
128
    '''Does not treat the document object as the root node's parent, since it's
129
    not a true element node'''
130
    parent_ = node.parentNode
131
    if parent_ != None and is_elem(parent_): return parent_
132
    else: return None
133

    
134
class NodeParentIter:
135
    '''See parent() for special treatment of root node.
136
    Note that the first element returned is the current node, not its parent.'''
137
    def __init__(self, node): self.node = node
138
    
139
    def __iter__(self): return self
140
    
141
    def curr(self):
142
        if self.node != None: return self.node
143
        else: raise StopIteration
144
    
145
    def next(self):
146
        node = self.curr()
147
        self.node = parent(self.node)
148
        return node
149

    
150
##### Element nodes containing text
151

    
152
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
153

    
154
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
155

    
156
def value_node(node):
157
    if is_elem(node):
158
        iter_ = NodeIter(node)
159
        util.skip(iter_, is_comment)
160
        try: return iter_.next()
161
        except StopIteration: return None
162
    else: return node
163

    
164
def value(node):
165
    return util.do_ignore_none(lambda n: n.nodeValue, value_node(node))
166

    
167
def is_whitespace(node): return is_text_node(node) and value(node).isspace()
168

    
169
def set_value(node, value):
170
    value_node_ = value_node(node)
171
    if value != None:
172
        if value_node_ != None:
173
            value_node_.nodeValue = value
174
        else:
175
            assert is_elem(node)
176
            node.appendChild(node.ownerDocument.createTextNode(value))
177
    else: node.nodeValue = value
178

    
179
class NodeTextEntryIter:
180
    def __init__(self, node): self.iter_ = NodeElemIter(node)
181
    
182
    def __iter__(self): return self
183
    
184
    def next(self):
185
        util.skip(self.iter_, is_empty)
186
        entry = self.iter_.next()
187
        if is_text(entry): value_ = value(entry)
188
        else:
189
            assert has_one_child(entry) # TODO: convert to an exception
190
            value_ = entry.firstChild
191
        return (entry.tagName, value_)
192

    
193
def is_text_node_entry(val): return util.is_str(val[1])
194

    
195
class TextEntryOnlyIter(util.CheckedIter):
196
    def __init__(self, iterable):
197
        util.CheckedIter.__init__(self, is_text_node_entry, iterable)
198

    
199
##### IDs
200

    
201
def get_id(node):
202
    '''If the node doesn't have an ID, assumes the node itself is the ID.
203
    @return None if the node doesn't have an ID or a value
204
    '''
205
    id_ = node.getAttribute('id')
206
    if id_ != '': return id_
207
    else: return value(node) # assume the node itself is the ID
208

    
209
def set_id(node, id_): node.setAttribute('id', id_)
210

    
211
##### Child nodes
212

    
213
def set_child(node, name, value):
214
    '''Note: does not remove any existing child of the same name'''
215
    child = node.ownerDocument.createElement(name)
216
    set_value(child, value)
217
    node.appendChild(child)
218

    
219
def by_tag_name(node, name, last_only=False, ignore_namespace=False):
220
    '''last_only optimization returns only the last matching node'''
221
    if ignore_namespace: filter_name = strip_namespace
222
    else: filter_name = lambda name: name
223
    name = filter_name(name)
224
    
225
    children = []
226
    if last_only: iter_ = NodeElemReverseIter(node)
227
    else: iter_ = NodeElemIter(node)
228
    for child in iter_:
229
        if filter_name(child.tagName) == name:
230
            children.append(child)
231
            if last_only: break
232
    return children
233

    
234
##### XML documents
235

    
236
def create_doc(root='_'):
237
    return minidom.getDOMImplementation().createDocument(None, root, None)
238

    
239
##### Printing XML
240

    
241
prettyxml_config = dict(addindent='    ', newl='\n')
242
toprettyxml_config = prettyxml_config.copy()
243
util.rename_key(toprettyxml_config, 'addindent', 'indent')
244

    
245
##### minidom modifications
246

    
247
#### Module
248

    
249
minidom._write_data = lambda writer, data: writer.write(escape(data))
250

    
251
minidom.Node.__iter__ = lambda self: NodeIter(self)
252

    
253
def __Node_str(self):
254
    return strings.remove_extra_newl(self.toprettyxml(**toprettyxml_config))
255
minidom.Node.__str__ = __Node_str
256
minidom.Node.__repr__ = __Node_str
257
minidom.Element.__repr__ = __Node_str
258

    
259
#### Node
260

    
261
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
262

    
263
def __Node_clear(self):
264
    while not is_empty(self): self.pop()
265
minidom.Node.clear = __Node_clear
266

    
267
#### Text
268

    
269
__Text_writexml_orig = minidom.Text.writexml
270
def __Text_writexml(self, *args, **kw_args):
271
    if is_whitespace(self): pass # we add our own whitespace
272
    else: __Text_writexml_orig(self, *args, **kw_args)
273
minidom.Text.writexml = __Text_writexml
274

    
275
#### Attr
276

    
277
def __Attr_str(self): return escape(self.name)+'="'+escape(self.value)+'"'
278
minidom.Attr.__str__ = __Attr_str
279
minidom.Attr.__repr__ = __Attr_str
280

    
281
#### Element
282

    
283
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
284
    writer.write(indent+'<'+escape(self.tagName))
285
    for attr_idx in xrange(self.attributes.length):
286
        writer.write(' '+str(self.attributes.item(attr_idx)))
287
    writer.write('>'+newl)
288
minidom.Element.write_opening = __Element_write_opening
289

    
290
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
291
    writer.write('</'+escape(self.tagName)+'>'+newl)
292
minidom.Element.write_closing = __Element_write_closing
293

    
294
__Element_writexml_orig = minidom.Element.writexml
295
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
296
    if isinstance(indent, int): indent = addindent*indent
297
    if is_simple(self):
298
        writer.write(indent)
299
        __Element_writexml_orig(self, writer)
300
        writer.write(newl)
301
    else: __Element_writexml_orig(self, writer, indent, addindent, newl)
302
minidom.Element.writexml = __Element_writexml
303

    
304
#### Document
305

    
306
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
307
    encoding=None):
308
    xmlDecl = '<?xml version="1.0" '
309
    if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
310
    xmlDecl += '?>'+newl
311
    writer.write(xmlDecl)
312
    assert has_one_child(self)
313
    assert is_elem(self.firstChild)
314
    self.firstChild.write_opening(writer, indent, addindent, newl)
315
minidom.Document.write_opening = __Document_write_opening
316

    
317
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
318
    self.firstChild.write_closing(writer, indent, addindent, newl)
319
minidom.Document.write_closing = __Document_write_closing
(29-29/33)