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

    
10
def escape(str_):
11
    return strings.to_unicode(cgi.escape(str_, True)).encode('ascii',
12
        'xmlcharrefreplace')
13

    
14
def unescape(str_): return HTMLParser().unescape(str_)
15

    
16
def get_id(node): return node.getAttribute('id')
17

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

    
20
def is_empty(node): return node.firstChild == None
21

    
22
def is_elem(node): return node.nodeType == Node.ELEMENT_NODE
23

    
24
class NodeElemIter:
25
    def __init__(self, node): self.child = node.firstChild
26
    
27
    def __iter__(self): return self
28
    
29
    def curr(self):
30
        while self.child != None:
31
            if is_elem(self.child): return self.child
32
            self.child = self.child.nextSibling
33
        raise StopIteration
34
    
35
    def next(self):
36
        child = self.curr()
37
        self.child = self.child.nextSibling
38
        return child
39

    
40
def first_elem(node): return NodeElemIter(node).next()
41

    
42
class NodeElemReverseIter:
43
    def __init__(self, node): self.child = node.lastChild
44
    
45
    def __iter__(self): return self
46
    
47
    def curr(self):
48
        while self.child != None:
49
            if is_elem(self.child): return self.child
50
            self.child = self.child.previousSibling
51
        raise StopIteration
52
    
53
    def next(self):
54
        child = self.curr()
55
        self.child = self.child.previousSibling
56
        return child
57

    
58
def last_elem(node): return NodeElemReverseIter(node).next()
59

    
60
class NodeParentIter:
61
    def __init__(self, node): self.node = node
62
    
63
    def __iter__(self): return self
64
    
65
    def curr(self):
66
        if self.node != None and is_elem(self.node): return self.node
67
        raise StopIteration
68
    
69
    def next(self):
70
        node = self.curr()
71
        self.node = self.node.parentNode
72
        return node
73

    
74
def is_text_node(node): return node.nodeType == Node.TEXT_NODE
75

    
76
def is_text(node):
77
    child = node.firstChild
78
    return child != None and child.nextSibling == None and is_text_node(child)
79

    
80
def value(node):
81
    if node.firstChild != None: return node.firstChild.nodeValue
82
    else: return node.nodeValue
83

    
84
def set_value(node, value):
85
    if is_elem(node): node.appendChild(node.ownerDocument.createTextNode(value))
86
    else: node.nodeValue = value
87

    
88
class NodeTextEntryIter:
89
    def __init__(self, node): self.iter_ = NodeElemIter(node)
90
    
91
    def __iter__(self): return self
92
    
93
    def curr(self):
94
        while True:
95
            child = self.iter_.curr()
96
            if is_text(child): return (child.tagName, value(child))
97
            self.iter_.next()
98
    
99
    def next(self):
100
        entry = self.curr()
101
        self.iter_.next()
102
        return entry
103

    
104
def set_child(node, name, value):
105
    '''Note: does not remove any existing child of the same name'''
106
    child = node.ownerDocument.createElement(name)
107
    set_value(child, value)
108
    node.appendChild(child)
109

    
110
def replace(old_node, new_node):
111
    old_node.parentNode.replaceChild(new_node, old_node) # note order reversed
112

    
113
def replace_with_text(node, str_):
114
    replace(node, node.ownerDocument.createTextNode(str_))
115

    
116
def by_tag_name(node, name, last_only=False):
117
    '''last_only optimization returns last matching node'''
118
    children = []
119
    for child in NodeElemReverseIter(node):
120
        if child.tagName == name:
121
            children.append(child)
122
            if last_only: break
123
    return children
124

    
125
def create_doc(root='_'):
126
    return minidom.getDOMImplementation().createDocument(None, root,
127
        None)
128

    
129
def writexml(writer, node): node.writexml(writer, addindent='    ', newl='\n')
130

    
131
# minidom modifications
132

    
133
minidom._write_data = lambda writer, data: writer.write(escape(data))
134

    
135
def __write_opening(self, writer, indent='', addindent='', newl=''):
136
    writer.write(indent+'<'+self.tagName)
137
    for attr_idx in xrange(self.attributes.length):
138
        attr = self.attributes.item(attr_idx)
139
        writer.write(' '+attr.name+'='+escape(attr.value))
140
    writer.write('>'+newl)
141
minidom.Element.write_opening = __write_opening
142

    
143
def __write_closing(self, writer, indent='', addindent='', newl=''):
144
    writer.write('</'+self.tagName+'>'+newl)
145
minidom.Element.write_closing = __write_closing
146

    
147
_writexml_orig = minidom.Element.writexml
148
def __writexml(self, writer, indent='', addindent='', newl=''):
149
    if is_text(self):
150
        self.write_opening(writer, indent, addindent, '') # no newline
151
        writer.write(escape(value(self)))
152
        self.write_closing(writer, indent, addindent, newl)
153
    else: _writexml_orig(self, writer, indent, addindent, newl)
154
minidom.Element.writexml = __writexml
155

    
156
minidom.Node.__str__ = lambda self: self.toxml()
(9-9/11)