1 |
21
|
aaronmk
|
# XML DOM tree manipulation
|
2 |
|
|
|
3 |
|
|
from xml.dom import Node
|
4 |
|
|
|
5 |
|
|
def name_of(node): return node.tagName.lower()
|
6 |
|
|
|
7 |
|
|
def get_id(node): return node.getAttribute('id')
|
8 |
|
|
|
9 |
|
|
def set_id(node, id_): node.setAttribute('id', id_)
|
10 |
|
|
|
11 |
|
|
class NodeElemIter:
|
12 |
|
|
def __init__(self, node): self.child = node.firstChild
|
13 |
|
|
|
14 |
|
|
def __iter__(self): return self
|
15 |
|
|
|
16 |
|
|
def curr(self):
|
17 |
|
|
while self.child != None:
|
18 |
|
|
if self.child.nodeType == Node.ELEMENT_NODE: return self.child
|
19 |
|
|
self.child = self.child.nextSibling
|
20 |
|
|
raise StopIteration
|
21 |
|
|
|
22 |
|
|
def next(self):
|
23 |
|
|
child = self.curr()
|
24 |
|
|
self.child = self.child.nextSibling
|
25 |
|
|
return child
|
26 |
|
|
|
27 |
|
|
def first_elem(node): return NodeElemIter(node).next()
|
28 |
|
|
|
29 |
|
|
class NodeElemReverseIter:
|
30 |
|
|
def __init__(self, node): self.child = node.lastChild
|
31 |
|
|
|
32 |
|
|
def __iter__(self): return self
|
33 |
|
|
|
34 |
|
|
def curr(self):
|
35 |
|
|
while self.child != None:
|
36 |
|
|
if self.child.nodeType == Node.ELEMENT_NODE: return self.child
|
37 |
|
|
self.child = self.child.previousSibling
|
38 |
|
|
raise StopIteration
|
39 |
|
|
|
40 |
|
|
def next(self):
|
41 |
|
|
child = self.curr()
|
42 |
|
|
self.child = self.child.previousSibling
|
43 |
|
|
return child
|
44 |
|
|
|
45 |
|
|
def last_elem(node): return NodeElemReverseIter(node).next()
|
46 |
|
|
|
47 |
|
|
class NodeParentIter:
|
48 |
|
|
def __init__(self, node): self.node = node
|
49 |
|
|
|
50 |
|
|
def __iter__(self): return self
|
51 |
|
|
|
52 |
|
|
def curr(self):
|
53 |
|
|
if self.node != None and self.node.nodeType == Node.ELEMENT_NODE:
|
54 |
|
|
return self.node
|
55 |
|
|
raise StopIteration
|
56 |
|
|
|
57 |
|
|
def next(self):
|
58 |
|
|
node = self.curr()
|
59 |
|
|
self.node = self.node.parentNode
|
60 |
|
|
return node
|
61 |
|
|
|
62 |
|
|
def is_text(node):
|
63 |
|
|
for child in NodeElemIter(node): return False # has an element node
|
64 |
|
|
return True
|
65 |
|
|
|
66 |
|
|
def value(node):
|
67 |
|
|
if node.firstChild != None: return node.firstChild.nodeValue.strip()
|
68 |
|
|
else: return node.nodeValue
|
69 |
|
|
|
70 |
22
|
aaronmk
|
def set_value(doc, node, value):
|
71 |
|
|
if node.nodeType == Node.ELEMENT_NODE:
|
72 |
|
|
node.appendChild(doc.createTextNode(value))
|
73 |
|
|
else: node.nodeValue = value
|
74 |
|
|
|
75 |
|
|
def by_tag_name(node, name, last_only=False):
|
76 |
23
|
aaronmk
|
# last_only optimization returns last (most recently inserted) matching node
|
77 |
22
|
aaronmk
|
children = []
|
78 |
21
|
aaronmk
|
for child in NodeElemReverseIter(node):
|
79 |
22
|
aaronmk
|
if child.tagName == name:
|
80 |
|
|
children.append(child)
|
81 |
|
|
if last_only: break
|
82 |
|
|
return children
|