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
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
def get_id(node): return node.getAttribute('id')
18

    
19
def set_id(node, id_): node.setAttribute('id', id_)
20

    
21
def is_completely_empty(node): return node.firstChild == None
22

    
23
def has_one_child(node):
24
    return node.firstChild != None and node.firstChild.nextSibling == None
25

    
26
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
def is_comment(node): return node.nodeType == Node.COMMENT_NODE
41

    
42
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
43

    
44
def is_empty(node):
45
    for child in NodeIter(node):
46
        if not is_comment(child): return False
47
    return True
48

    
49
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
            if is_elem(self.child): return self.child
57
            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
def has_elems(node):
68
    try: first_elem(node); return True
69
    except StopIteration: return False
70

    
71
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
            if is_elem(self.child): return self.child
79
            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
        if self.node != None and is_elem(self.node): return self.node
96
        raise StopIteration
97
    
98
    def next(self):
99
        node = self.curr()
100
        self.node = self.node.parentNode
101
        return node
102

    
103
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
104

    
105
def is_text(node): return has_one_child(node) and is_text_node(node.firstChild)
106

    
107
def value(node):
108
    if node.firstChild != None: return node.firstChild.nodeValue
109
    else: return node.nodeValue
110

    
111
def set_value(node, value):
112
    if is_elem(node): node.appendChild(node.ownerDocument.createTextNode(value))
113
    else: node.nodeValue = value
114

    
115
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
            if is_text(child): return (child.tagName, value(child))
124
            self.iter_.next()
125
    
126
    def next(self):
127
        entry = self.curr()
128
        self.iter_.next()
129
        return entry
130

    
131
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
    set_value(child, value)
135
    node.appendChild(child)
136

    
137
def remove(node): node.parentNode.removeChild(node)
138

    
139
def replace(old_node, new_node):
140
    old_node.parentNode.replaceChild(new_node, old_node) # note order reversed
141

    
142
def replace_with_text(node, str_):
143
    replace(node, node.ownerDocument.createTextNode(str_))
144

    
145
def by_tag_name(node, name, last_only=False):
146
    '''last_only optimization returns last matching node'''
147
    children = []
148
    for child in NodeElemReverseIter(node):
149
        if child.tagName == name:
150
            children.append(child)
151
            if last_only: break
152
    return children
153

    
154
def create_doc(root='_'):
155
    return minidom.getDOMImplementation().createDocument(None, root, None)
156

    
157
prettyxml_config = dict(addindent='    ', newl='\n')
158
toprettyxml_config = prettyxml_config.copy()
159
util.rename_key(toprettyxml_config, 'addindent', 'indent')
160

    
161
# minidom modifications
162

    
163
minidom._write_data = lambda writer, data: writer.write(escape(data))
164

    
165
minidom.Node.__iter__ = lambda self: NodeIter(self)
166

    
167
minidom.Node.__str__ = lambda self: self.toprettyxml(**toprettyxml_config)
168

    
169
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
def __Element_write_opening(self, writer, indent='', addindent='', newl=''):
176
    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
minidom.Element.write_opening = __Element_write_opening
182

    
183
def __Element_write_closing(self, writer, indent='', addindent='', newl=''):
184
    writer.write('</'+self.tagName+'>'+newl)
185
minidom.Element.write_closing = __Element_write_closing
186

    
187
_writexml_orig = minidom.Element.writexml
188
def __Element_writexml(self, writer, indent='', addindent='', newl=''):
189
    if isinstance(indent, int): indent = addindent*indent
190
    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
    else: _writexml_orig(self, writer, indent, addindent, newl)
195
minidom.Element.writexml = __Element_writexml
196

    
197
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
(9-9/11)