1
|
# 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 NodeParentIter:
|
30
|
def __init__(self, node): self.node = node
|
31
|
|
32
|
def __iter__(self): return self
|
33
|
|
34
|
def curr(self):
|
35
|
if self.node != None and self.node.nodeType == Node.ELEMENT_NODE:
|
36
|
return self.node
|
37
|
raise StopIteration
|
38
|
|
39
|
def next(self):
|
40
|
node = self.curr()
|
41
|
self.node = self.node.parentNode
|
42
|
return node
|
43
|
|
44
|
def is_text(node):
|
45
|
for child in NodeElemIter(node): return False # has an element node
|
46
|
return True
|
47
|
|
48
|
def value(node):
|
49
|
if node.firstChild != None: return node.firstChild.nodeValue.strip()
|
50
|
else: return None
|