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 28 aaronmk
import xml.dom.minidom
7 21 aaronmk
8 73 aaronmk
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 21 aaronmk
def name_of(node): return node.tagName.lower()
17
18
def get_id(node): return node.getAttribute('id')
19
20
def set_id(node, id_): node.setAttribute('id', id_)
21
22 135 aaronmk
def is_empty(node): return node.firstChild == None
23
24 21 aaronmk
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 self.child.nodeType == Node.ELEMENT_NODE: 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 self.child.nodeType == Node.ELEMENT_NODE: 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 self.node.nodeType == Node.ELEMENT_NODE:
67
            return self.node
68
        raise StopIteration
69
70
    def next(self):
71
        node = self.curr()
72
        self.node = self.node.parentNode
73
        return node
74
75
def is_text(node):
76
    for child in NodeElemIter(node): return False # has an element node
77
    return True
78
79
def value(node):
80 29 aaronmk
    if node.firstChild != None: return node.firstChild.nodeValue
81 21 aaronmk
    else: return node.nodeValue
82
83 22 aaronmk
def set_value(doc, node, value):
84
    if node.nodeType == Node.ELEMENT_NODE:
85
        node.appendChild(doc.createTextNode(value))
86
    else: node.nodeValue = value
87
88 86 aaronmk
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 (name_of(child), value(child))
97
            self.iter_.next()
98
99
    def next(self):
100
        entry = self.curr()
101
        self.iter_.next()
102
        return entry
103
104 135 aaronmk
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(node.ownerDocument, child, value)
108
    node.appendChild(child)
109
110 86 aaronmk
def replace(old_node, new_node):
111
    old_node.parentNode.replaceChild(new_node, old_node) # note order reversed
112
113
def replace_with_text(doc, node, str_): replace(node, doc.createTextNode(str_))
114
115 22 aaronmk
def by_tag_name(node, name, last_only=False):
116 135 aaronmk
    '''last_only optimization returns last matching node'''
117 22 aaronmk
    children = []
118 21 aaronmk
    for child in NodeElemReverseIter(node):
119 22 aaronmk
        if child.tagName == name:
120
            children.append(child)
121
            if last_only: break
122
    return children
123 28 aaronmk
124 133 aaronmk
def create_doc(root='_'):
125
    return xml.dom.minidom.getDOMImplementation().createDocument(None, root,
126
        None)
127
128 135 aaronmk
def writexml(writer, node): node.writexml(writer, addindent='    ', newl='\n')
129
130 73 aaronmk
# xml.dom.minidom modifications
131
132
def _write_data(writer, data): writer.write(escape(data))
133
134
xml.dom.minidom._write_data = _write_data
135
136 28 aaronmk
_writexml_orig = xml.dom.minidom.Element.writexml
137
138
def _writexml(self, writer, indent="", addindent="", newl=""):
139 36 aaronmk
    if self.firstChild != None and self.firstChild.nextSibling == None\
140
    and self.firstChild.nodeType == Node.TEXT_NODE: # a single text node
141 28 aaronmk
        writer.write(indent+'<'+self.tagName)
142 70 aaronmk
        for attr_idx in xrange(self.attributes.length):
143 28 aaronmk
            attr = self.attributes.item(attr_idx)
144 73 aaronmk
            writer.write(' '+attr.name+'='+escape(attr.value))
145
        writer.write('>'+escape(value(self))+'</'+self.tagName+'>'+newl)
146 28 aaronmk
    else: _writexml_orig(self, writer, indent, addindent, newl)
147
148
xml.dom.minidom.Element.writexml = _writexml