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