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
class NodeParentIter:
107
    def __init__(self, node): self.node = node
108
    
109
    def __iter__(self): return self
110
    
111
    def curr(self):
112
        if self.node != None and is_elem(self.node): return self.node
113
        raise StopIteration
114
    
115
    def next(self):
116
        node = self.curr()
117
        self.node = self.node.parentNode
118
        return node
119

    
120
##### Element nodes containing text
121

    
122
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
123

    
124
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
125

    
126
def value(node):
127
    if node.firstChild != None: return node.firstChild.nodeValue
128
    else: return node.nodeValue
129

    
130
def set_value(node, value):
131
    if is_elem(node): node.appendChild(node.ownerDocument.createTextNode(value))
132
    else: node.nodeValue = value
133

    
134
class NodeTextEntryIter:
135
    def __init__(self, node): self.iter_ = NodeElemIter(node)
136
    
137
    def __iter__(self): return self
138
    
139
    def curr(self):
140
        entry = self.iter_.curr()
141
        if is_text(entry): value_ = value(entry)
142
        else:
143
            assert has_one_child(entry) # TODO: convert to an exception
144
            value_ = entry.firstChild
145
        return (entry.tagName, value_)
146
    
147
    def next(self):
148
        entry = self.curr()
149
        self.iter_.next()
150
        return entry
151

    
152
def is_text_node_entry(val): return util.is_str(val[1])
153

    
154
class TextEntryOnlyIter(util.CheckedIter):
155
    def __init__(self, iterable):
156
        util.CheckedIter.__init__(self, is_text_node_entry, iterable)
157

    
158
##### Modifying/replacing a node
159

    
160
def set_child(node, name, value):
161
    '''Note: does not remove any existing child of the same name'''
162
    child = node.ownerDocument.createElement(name)
163
    set_value(child, value)
164
    node.appendChild(child)
165

    
166
def remove(node): node.parentNode.removeChild(node)
167

    
168
def replace(old_node, new_node):
169
    old_node.parentNode.replaceChild(new_node, old_node) # note order reversed
170

    
171
def replace_with_text(node, new):
172
    if util.is_str(new): new = node.ownerDocument.createTextNode(new)
173
    replace(node, new)
174

    
175
##### Searching child nodes
176

    
177
def by_tag_name(node, name, last_only=False):
178
    '''last_only optimization returns last matching node'''
179
    children = []
180
    for child in NodeElemReverseIter(node):
181
        if child.tagName == name:
182
            children.append(child)
183
            if last_only: break
184
    return children
185

    
186
##### XML documents
187

    
188
def create_doc(root='_'):
189
    return minidom.getDOMImplementation().createDocument(None, root, None)
190

    
191
##### Printing XML
192

    
193
prettyxml_config = dict(addindent='    ', newl='\n')
194
toprettyxml_config = prettyxml_config.copy()
195
util.rename_key(toprettyxml_config, 'addindent', 'indent')
196

    
197
##### minidom modifications
198

    
199
minidom._write_data = lambda writer, data: writer.write(escape(data))
200

    
201
minidom.Node.__iter__ = lambda self: NodeIter(self)
202

    
203
def __Node_str(self): return self.toprettyxml(**toprettyxml_config)
204
minidom.Node.__str__ = __Node_str
205
minidom.Node.__repr__ = __Node_str
206
minidom.Element.__repr__ = __Node_str
207

    
208
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
209

    
210
def __Node_clear(self):
211
    while not is_empty(self): self.pop()
212
minidom.Node.clear = __Node_clear
213

    
214
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
215
    writer.write(indent+'<'+self.tagName)
216
    for attr_idx in xrange(self.attributes.length):
217
        attr = self.attributes.item(attr_idx)
218
        writer.write(' '+attr.name+'='+escape(attr.value))
219
    writer.write('>'+newl)
220
minidom.Element.write_opening = __Element_write_opening
221

    
222
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
223
    writer.write('</'+self.tagName+'>'+newl)
224
minidom.Element.write_closing = __Element_write_closing
225

    
226
_writexml_orig = minidom.Element.writexml
227
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
228
    if isinstance(indent, int): indent = addindent*indent
229
    if is_simple(self):
230
        writer.write(indent)
231
        _writexml_orig(self, writer)
232
        writer.write(newl)
233
    else: _writexml_orig(self, writer, indent, addindent, newl)
234
minidom.Element.writexml = __Element_writexml
235

    
236
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
237
    encoding=None):
238
    xmlDecl = '<?xml version="1.0" '
239
    if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
240
    xmlDecl += '?>'+newl
241
    writer.write(xmlDecl)
242
    assert has_one_child(self)
243
    assert is_elem(self.firstChild)
244
    self.firstChild.write_opening(writer, indent, addindent, newl)
245
minidom.Document.write_opening = __Document_write_opening
246

    
247
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
248
    self.firstChild.write_closing(writer, indent, addindent, newl)
249
minidom.Document.write_closing = __Document_write_closing
(12-12/14)