Project

General

Profile

1 21 aaronmk
# XML DOM tree manipulation
2
3 73 aaronmk
import cgi
4
from HTMLParser import HTMLParser
5 21 aaronmk
from xml.dom import Node
6 299 aaronmk
import xml.dom.minidom as minidom
7 21 aaronmk
8 73 aaronmk
import strings
9 331 aaronmk
import util
10 73 aaronmk
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 455 aaronmk
#####
18
19 21 aaronmk
def get_id(node): return node.getAttribute('id')
20
21
def set_id(node, id_): node.setAttribute('id', id_)
22
23 455 aaronmk
#####
24
25 453 aaronmk
def is_completely_empty(node): return node.firstChild == None
26 135 aaronmk
27 301 aaronmk
def has_one_child(node):
28
    return node.firstChild != None and node.firstChild.nextSibling == None
29
30 305 aaronmk
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 455 aaronmk
#####
45
46 453 aaronmk
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 455 aaronmk
#####
54
55
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
56
57 21 aaronmk
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 298 aaronmk
            if is_elem(self.child): return self.child
65 21 aaronmk
            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 450 aaronmk
def has_elems(node):
76
    try: first_elem(node); return True
77
    except StopIteration: return False
78
79 21 aaronmk
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 298 aaronmk
            if is_elem(self.child): return self.child
87 21 aaronmk
            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 298 aaronmk
        if self.node != None and is_elem(self.node): return self.node
104 21 aaronmk
        raise StopIteration
105
106
    def next(self):
107
        node = self.curr()
108
        self.node = self.node.parentNode
109
        return node
110
111 455 aaronmk
#####
112
113 298 aaronmk
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
114
115 301 aaronmk
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
116 21 aaronmk
117
def value(node):
118 29 aaronmk
    if node.firstChild != None: return node.firstChild.nodeValue
119 21 aaronmk
    else: return node.nodeValue
120
121 143 aaronmk
def set_value(node, value):
122 298 aaronmk
    if is_elem(node): node.appendChild(node.ownerDocument.createTextNode(value))
123 22 aaronmk
    else: node.nodeValue = value
124
125 86 aaronmk
class NodeTextEntryIter:
126
    def __init__(self, node): self.iter_ = NodeElemIter(node)
127
128
    def __iter__(self): return self
129
130
    def curr(self):
131 456 aaronmk
        child = self.iter_.curr()
132
        name = child.tagName
133
        if is_text(child): child = value(child)
134
        return (name, child)
135 86 aaronmk
136
    def next(self):
137
        entry = self.curr()
138
        self.iter_.next()
139
        return entry
140
141 455 aaronmk
#####
142
143 135 aaronmk
def set_child(node, name, value):
144
    '''Note: does not remove any existing child of the same name'''
145
    child = node.ownerDocument.createElement(name)
146 143 aaronmk
    set_value(child, value)
147 135 aaronmk
    node.appendChild(child)
148
149 435 aaronmk
def remove(node): node.parentNode.removeChild(node)
150
151 86 aaronmk
def replace(old_node, new_node):
152
    old_node.parentNode.replaceChild(new_node, old_node) # note order reversed
153
154 142 aaronmk
def replace_with_text(node, str_):
155
    replace(node, node.ownerDocument.createTextNode(str_))
156 86 aaronmk
157 455 aaronmk
#####
158
159 22 aaronmk
def by_tag_name(node, name, last_only=False):
160 135 aaronmk
    '''last_only optimization returns last matching node'''
161 22 aaronmk
    children = []
162 21 aaronmk
    for child in NodeElemReverseIter(node):
163 22 aaronmk
        if child.tagName == name:
164
            children.append(child)
165
            if last_only: break
166
    return children
167 28 aaronmk
168 455 aaronmk
#####
169
170 133 aaronmk
def create_doc(root='_'):
171 303 aaronmk
    return minidom.getDOMImplementation().createDocument(None, root, None)
172 133 aaronmk
173 455 aaronmk
#####
174
175 304 aaronmk
prettyxml_config = dict(addindent='    ', newl='\n')
176 331 aaronmk
toprettyxml_config = prettyxml_config.copy()
177
util.rename_key(toprettyxml_config, 'addindent', 'indent')
178 304 aaronmk
179 455 aaronmk
#####
180
181 299 aaronmk
# minidom modifications
182 73 aaronmk
183 299 aaronmk
minidom._write_data = lambda writer, data: writer.write(escape(data))
184 73 aaronmk
185 305 aaronmk
minidom.Node.__iter__ = lambda self: NodeIter(self)
186
187 331 aaronmk
minidom.Node.__str__ = lambda self: self.toprettyxml(**toprettyxml_config)
188 301 aaronmk
189 315 aaronmk
minidom.Node.pop = lambda self: self.removeChild(self.lastChild)
190
191
def __Node_clear(self):
192
    while not is_empty(self): self.pop()
193
minidom.Node.clear = __Node_clear
194
195 301 aaronmk
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
196 298 aaronmk
    writer.write(indent+'<'+self.tagName)
197
    for attr_idx in xrange(self.attributes.length):
198
        attr = self.attributes.item(attr_idx)
199
        writer.write(' '+attr.name+'='+escape(attr.value))
200
    writer.write('>'+newl)
201 301 aaronmk
minidom.Element.write_opening = __Element_write_opening
202 73 aaronmk
203 301 aaronmk
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
204 298 aaronmk
    writer.write('</'+self.tagName+'>'+newl)
205 301 aaronmk
minidom.Element.write_closing = __Element_write_closing
206 298 aaronmk
207 299 aaronmk
_writexml_orig = minidom.Element.writexml
208 301 aaronmk
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
209 306 aaronmk
    if isinstance(indent, int): indent = addindent*indent
210 298 aaronmk
    if is_text(self):
211
        self.write_opening(writer, indent, addindent, '') # no newline
212
        writer.write(escape(value(self)))
213
        self.write_closing(writer, indent, addindent, newl)
214 28 aaronmk
    else: _writexml_orig(self, writer, indent, addindent, newl)
215 301 aaronmk
minidom.Element.writexml = __Element_writexml
216 28 aaronmk
217 301 aaronmk
def __Document_write_opening(self, writer, indent='', addindent='', newl='',
218
    encoding=None):
219
    xmlDecl = '<?xml version="1.0" '
220
    if encoding != None: xmlDecl += 'encoding="'+escape(encoding)+'"'
221
    xmlDecl += '?>'+newl
222
    writer.write(xmlDecl)
223
    assert has_one_child(self)
224
    assert is_elem(self.firstChild)
225
    self.firstChild.write_opening(writer, indent, addindent, newl)
226
minidom.Document.write_opening = __Document_write_opening
227
228
def __Document_write_closing(self, writer, indent='', addindent='', newl=''):
229
    self.firstChild.write_closing(writer, indent, addindent, newl)
230
minidom.Document.write_closing = __Document_write_closing