Project

General

Profile

1
# XML DOM tree manipulation
2

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

    
8
import strings
9
import util
10

    
11
##### Escaping input
12

    
13
def escape(str_):
14
    return strings.to_unicode(cgi.escape(str_, True)).encode('ascii',
15
        'xmlcharrefreplace')
16

    
17
def unescape(str_): return HTMLParser().unescape(str_)
18

    
19
##### IDs
20

    
21
def get_id(node): return node.getAttribute('id')
22

    
23
def set_id(node, id_): node.setAttribute('id', id_)
24

    
25
##### Element node contents
26

    
27
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
28

    
29
def is_completely_empty(node): return node.firstChild == None
30

    
31
def has_one_child(node):
32
    return node.firstChild != None and node.firstChild.nextSibling == None
33

    
34
def is_simple(node):
35
    '''Whether every child recursively has no more than one child'''
36
    return (not is_elem(node) or is_completely_empty(node)
37
        or (has_one_child(node) and is_simple(node.firstChild)))
38

    
39
class NodeIter:
40
    def __init__(self, node): self.child = node.firstChild
41
    
42
    def __iter__(self): return self
43
    
44
    def curr(self):
45
        if self.child != None: return self.child
46
        raise StopIteration
47
    
48
    def next(self):
49
        child = self.curr()
50
        self.child = self.child.nextSibling
51
        return child
52

    
53
##### Comments
54

    
55
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
56

    
57
def is_empty(node):
58
    for child in NodeIter(node):
59
        if not is_comment(child): return False
60
    return True
61

    
62
##### Child nodes that are elements
63

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

    
80
def first_elem(node): return NodeElemIter(node).next()
81

    
82
def has_elems(node):
83
    try: first_elem(node); return True
84
    except StopIteration: return False
85

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

    
102
def last_elem(node): return NodeElemReverseIter(node).next()
103

    
104
##### Parent nodes
105

    
106
def parent(node):
107
    '''Does not treat the document object as the root node's parent, since it's
108
    not a true element node'''
109
    parent_ = node.parentNode
110
    if parent_ != None and is_elem(parent_): return parent_
111
    else: return None
112

    
113
class NodeParentIter:
114
    '''See parent() for special treatment of root node.
115
    Note that the first element returned is the current node, not its parent.'''
116
    def __init__(self, node): self.node = node
117
    
118
    def __iter__(self): return self
119
    
120
    def curr(self):
121
        if self.node != None: return self.node
122
        else: raise StopIteration
123
    
124
    def next(self):
125
        node = self.curr()
126
        self.node = parent(self.node)
127
        return node
128

    
129
##### Element nodes containing text
130

    
131
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
132

    
133
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
134

    
135
def value(node):
136
    if node.firstChild != None: return node.firstChild.nodeValue
137
    else: return node.nodeValue
138

    
139
def set_value(node, value):
140
    if is_elem(node): node.appendChild(node.ownerDocument.createTextNode(value))
141
    else: node.nodeValue = value
142

    
143
class NodeTextEntryIter:
144
    def __init__(self, node): self.iter_ = NodeElemIter(node)
145
    
146
    def __iter__(self): return self
147
    
148
    def curr(self):
149
        entry = self.iter_.curr()
150
        if is_text(entry): value_ = value(entry)
151
        elif is_empty(entry): value_ = None
152
        else:
153
            assert has_one_child(entry) # TODO: convert to an exception
154
            value_ = entry.firstChild
155
        return (entry.tagName, value_)
156
    
157
    def next(self):
158
        entry = self.curr()
159
        self.iter_.next()
160
        return entry
161

    
162
def is_text_node_entry(val): return util.is_str(val[1])
163

    
164
class TextEntryOnlyIter(util.CheckedIter):
165
    def __init__(self, iterable):
166
        util.CheckedIter.__init__(self, is_text_node_entry, iterable)
167

    
168
##### Modifying/replacing a node
169

    
170
def set_child(node, name, value):
171
    '''Note: does not remove any existing child of the same name'''
172
    child = node.ownerDocument.createElement(name)
173
    set_value(child, value)
174
    node.appendChild(child)
175

    
176
def remove(node): node.parentNode.removeChild(node)
177

    
178
def replace(old, new):
179
    '''@param new Node|None'''
180
    if new == None: old.parentNode.removeChild(old)
181
    else: old.parentNode.replaceChild(new, old) # note order reversed
182

    
183
def replace_with_text(node, new):
184
    if util.is_str(new): new = node.ownerDocument.createTextNode(new)
185
    replace(node, new)
186

    
187
##### Searching child nodes
188

    
189
def by_tag_name(node, name, last_only=False):
190
    '''last_only optimization returns last matching node'''
191
    children = []
192
    if last_only: iter_ = NodeElemReverseIter(node)
193
    else: iter_ = NodeElemIter(node)
194
    for child in iter_:
195
        if child.tagName == name:
196
            children.append(child)
197
            if last_only: break
198
    return children
199

    
200
##### XML documents
201

    
202
def create_doc(root='_'):
203
    return minidom.getDOMImplementation().createDocument(None, root, None)
204

    
205
##### Printing XML
206

    
207
prettyxml_config = dict(addindent='    ', newl='\n')
208
toprettyxml_config = prettyxml_config.copy()
209
util.rename_key(toprettyxml_config, 'addindent', 'indent')
210

    
211
##### minidom modifications
212

    
213
minidom._write_data = lambda writer, data: writer.write(escape(data))
214

    
215
minidom.Node.__iter__ = lambda self: NodeIter(self)
216

    
217
def __Node_str(self):
218
    return strings.remove_extra_newl(self.toprettyxml(**toprettyxml_config))
219
minidom.Node.__str__ = __Node_str
220
minidom.Node.__repr__ = __Node_str
221
minidom.Element.__repr__ = __Node_str
222

    
223
def __Attr_str(self): return self.name+'="'+escape(self.value)+'"'
224
minidom.Attr.__str__ = __Attr_str
225
minidom.Attr.__repr__ = __Attr_str
226

    
227
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
228

    
229
def __Node_clear(self):
230
    while not is_empty(self): self.pop()
231
minidom.Node.clear = __Node_clear
232

    
233
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
234
    writer.write(indent+'<'+self.tagName)
235
    for attr_idx in xrange(self.attributes.length):
236
        writer.write(' '+str(self.attributes.item(attr_idx)))
237
    writer.write('>'+newl)
238
minidom.Element.write_opening = __Element_write_opening
239

    
240
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
241
    writer.write('</'+self.tagName+'>'+newl)
242
minidom.Element.write_closing = __Element_write_closing
243

    
244
_writexml_orig = minidom.Element.writexml
245
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
246
    if isinstance(indent, int): indent = addindent*indent
247
    if is_simple(self):
248
        writer.write(indent)
249
        _writexml_orig(self, writer)
250
        writer.write(newl)
251
    else: _writexml_orig(self, writer, indent, addindent, newl)
252
minidom.Element.writexml = __Element_writexml
253

    
254
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
255
    encoding=None):
256
    xmlDecl = '<?xml version="1.0" '
257
    if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
258
    xmlDecl += '?>'+newl
259
    writer.write(xmlDecl)
260
    assert has_one_child(self)
261
    assert is_elem(self.firstChild)
262
    self.firstChild.write_opening(writer, indent, addindent, newl)
263
minidom.Document.write_opening = __Document_write_opening
264

    
265
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
266
    self.firstChild.write_closing(writer, indent, addindent, newl)
267
minidom.Document.write_closing = __Document_write_closing
(14-14/16)