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
|
def escape(str_):
|
12
|
return strings.to_unicode(cgi.escape(str_, True)).encode('ascii',
|
13
|
'xmlcharrefreplace')
|
14
|
|
15
|
def unescape(str_): return HTMLParser().unescape(str_)
|
16
|
|
17
|
#####
|
18
|
|
19
|
def get_id(node): return node.getAttribute('id')
|
20
|
|
21
|
def set_id(node, id_): node.setAttribute('id', id_)
|
22
|
|
23
|
#####
|
24
|
|
25
|
def is_completely_empty(node): return node.firstChild == None
|
26
|
|
27
|
def has_one_child(node):
|
28
|
return node.firstChild != None and node.firstChild.nextSibling == None
|
29
|
|
30
|
class NodeIter:
|
31
|
def __init__(self, node): self.child = node.firstChild
|
32
|
|
33
|
def __iter__(self): return self
|
34
|
|
35
|
def curr(self):
|
36
|
if self.child != None: return self.child
|
37
|
raise StopIteration
|
38
|
|
39
|
def next(self):
|
40
|
child = self.curr()
|
41
|
self.child = self.child.nextSibling
|
42
|
return child
|
43
|
|
44
|
#####
|
45
|
|
46
|
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
|
47
|
|
48
|
def is_empty(node):
|
49
|
for child in NodeIter(node):
|
50
|
if not is_comment(child): return False
|
51
|
return True
|
52
|
|
53
|
#####
|
54
|
|
55
|
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
|
56
|
|
57
|
class NodeElemIter:
|
58
|
def __init__(self, node): self.child = node.firstChild
|
59
|
|
60
|
def __iter__(self): return self
|
61
|
|
62
|
def curr(self):
|
63
|
while self.child != None:
|
64
|
if is_elem(self.child): return self.child
|
65
|
self.child = self.child.nextSibling
|
66
|
raise StopIteration
|
67
|
|
68
|
def next(self):
|
69
|
child = self.curr()
|
70
|
self.child = self.child.nextSibling
|
71
|
return child
|
72
|
|
73
|
def first_elem(node): return NodeElemIter(node).next()
|
74
|
|
75
|
def has_elems(node):
|
76
|
try: first_elem(node); return True
|
77
|
except StopIteration: return False
|
78
|
|
79
|
class NodeElemReverseIter:
|
80
|
def __init__(self, node): self.child = node.lastChild
|
81
|
|
82
|
def __iter__(self): return self
|
83
|
|
84
|
def curr(self):
|
85
|
while self.child != None:
|
86
|
if is_elem(self.child): return self.child
|
87
|
self.child = self.child.previousSibling
|
88
|
raise StopIteration
|
89
|
|
90
|
def next(self):
|
91
|
child = self.curr()
|
92
|
self.child = self.child.previousSibling
|
93
|
return child
|
94
|
|
95
|
def last_elem(node): return NodeElemReverseIter(node).next()
|
96
|
|
97
|
class NodeParentIter:
|
98
|
def __init__(self, node): self.node = node
|
99
|
|
100
|
def __iter__(self): return self
|
101
|
|
102
|
def curr(self):
|
103
|
if self.node != None and is_elem(self.node): return self.node
|
104
|
raise StopIteration
|
105
|
|
106
|
def next(self):
|
107
|
node = self.curr()
|
108
|
self.node = self.node.parentNode
|
109
|
return node
|
110
|
|
111
|
def is_simple(node):
|
112
|
'''Whether every child recursively has no more than one child'''
|
113
|
return (not is_elem(node) or is_completely_empty(node)
|
114
|
or (has_one_child(node) and is_simple(node.firstChild)))
|
115
|
|
116
|
#####
|
117
|
|
118
|
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
|
119
|
|
120
|
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
|
121
|
|
122
|
def value(node):
|
123
|
if node.firstChild != None: return node.firstChild.nodeValue
|
124
|
else: return node.nodeValue
|
125
|
|
126
|
def set_value(node, value):
|
127
|
if is_elem(node): node.appendChild(node.ownerDocument.createTextNode(value))
|
128
|
else: node.nodeValue = value
|
129
|
|
130
|
class NodeTextEntryIter:
|
131
|
def __init__(self, node): self.iter_ = NodeElemIter(node)
|
132
|
|
133
|
def __iter__(self): return self
|
134
|
|
135
|
def curr(self):
|
136
|
child = self.iter_.curr()
|
137
|
name = child.tagName
|
138
|
if is_text(child): child = value(child)
|
139
|
return (name, child)
|
140
|
|
141
|
def next(self):
|
142
|
entry = self.curr()
|
143
|
self.iter_.next()
|
144
|
return entry
|
145
|
|
146
|
def is_text_node_entry(val): return util.is_str(val[1])
|
147
|
|
148
|
class TextEntryOnlyIter(util.CheckedIter):
|
149
|
def __init__(self, iterable):
|
150
|
util.CheckedIter.__init__(self, is_text_node_entry, iterable)
|
151
|
|
152
|
#####
|
153
|
|
154
|
def set_child(node, name, value):
|
155
|
'''Note: does not remove any existing child of the same name'''
|
156
|
child = node.ownerDocument.createElement(name)
|
157
|
set_value(child, value)
|
158
|
node.appendChild(child)
|
159
|
|
160
|
def remove(node): node.parentNode.removeChild(node)
|
161
|
|
162
|
def replace(old_node, new_node):
|
163
|
old_node.parentNode.replaceChild(new_node, old_node) # note order reversed
|
164
|
|
165
|
def replace_with_text(node, new):
|
166
|
if util.is_str(new): new = node.ownerDocument.createTextNode(new)
|
167
|
replace(node, new)
|
168
|
|
169
|
#####
|
170
|
|
171
|
def by_tag_name(node, name, last_only=False):
|
172
|
'''last_only optimization returns last matching node'''
|
173
|
children = []
|
174
|
for child in NodeElemReverseIter(node):
|
175
|
if child.tagName == name:
|
176
|
children.append(child)
|
177
|
if last_only: break
|
178
|
return children
|
179
|
|
180
|
#####
|
181
|
|
182
|
def create_doc(root='_'):
|
183
|
return minidom.getDOMImplementation().createDocument(None, root, None)
|
184
|
|
185
|
#####
|
186
|
|
187
|
prettyxml_config = dict(addindent=' ', newl='\n')
|
188
|
toprettyxml_config = prettyxml_config.copy()
|
189
|
util.rename_key(toprettyxml_config, 'addindent', 'indent')
|
190
|
|
191
|
#####
|
192
|
|
193
|
# minidom modifications
|
194
|
|
195
|
minidom._write_data = lambda writer, data: writer.write(escape(data))
|
196
|
|
197
|
minidom.Node.__iter__ = lambda self: NodeIter(self)
|
198
|
|
199
|
def __Node_str(self): return self.toprettyxml(**toprettyxml_config)
|
200
|
minidom.Node.__str__ = __Node_str
|
201
|
minidom.Node.__repr__ = __Node_str
|
202
|
minidom.Element.__repr__ = __Node_str
|
203
|
|
204
|
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
|
205
|
|
206
|
def __Node_clear(self):
|
207
|
while not is_empty(self): self.pop()
|
208
|
minidom.Node.clear = __Node_clear
|
209
|
|
210
|
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
|
211
|
writer.write(indent+'<'+self.tagName)
|
212
|
for attr_idx in xrange(self.attributes.length):
|
213
|
attr = self.attributes.item(attr_idx)
|
214
|
writer.write(' '+attr.name+'='+escape(attr.value))
|
215
|
writer.write('>'+newl)
|
216
|
minidom.Element.write_opening = __Element_write_opening
|
217
|
|
218
|
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
|
219
|
writer.write('</'+self.tagName+'>'+newl)
|
220
|
minidom.Element.write_closing = __Element_write_closing
|
221
|
|
222
|
_writexml_orig = minidom.Element.writexml
|
223
|
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
|
224
|
if isinstance(indent, int): indent = addindent*indent
|
225
|
if is_simple(self):
|
226
|
writer.write(indent)
|
227
|
_writexml_orig(self, writer)
|
228
|
writer.write(newl)
|
229
|
else: _writexml_orig(self, writer, indent, addindent, newl)
|
230
|
minidom.Element.writexml = __Element_writexml
|
231
|
|
232
|
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
|
233
|
encoding=None):
|
234
|
xmlDecl = '<?xml version="1.0" '
|
235
|
if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
|
236
|
xmlDecl += '?>'+newl
|
237
|
writer.write(xmlDecl)
|
238
|
assert has_one_child(self)
|
239
|
assert is_elem(self.firstChild)
|
240
|
self.firstChild.write_opening(writer, indent, addindent, newl)
|
241
|
minidom.Document.write_opening = __Document_write_opening
|
242
|
|
243
|
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
|
244
|
self.firstChild.write_closing(writer, indent, addindent, newl)
|
245
|
minidom.Document.write_closing = __Document_write_closing
|