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