Merge branch 'master' into python3
[wrw.git] / wrw / sp / cons.py
... / ...
CommitLineData
1import xml.dom.minidom
2
3class node(object):
4 def __str__(self):
5 doc = xml.dom.minidom.Document()
6 return self.__todom__(doc).toxml()
7
8class text(node, str):
9 def __todom__(self, doc):
10 return doc.createTextNode(self)
11
12class raw(node, str):
13 def __todom__(self, doc):
14 raise Exception("Cannot convert raw code to DOM objects")
15
16class element(node):
17 def __init__(self, ns, name, ctx):
18 self.ns = ns
19 self.name = str(name)
20 self.ctx = ctx
21 self.attrs = {}
22 self.children = []
23
24 def __call__(self, *children, **attrs):
25 for child in children:
26 self.children.append(self.ctx.nodefrom(child))
27 for k, v in attrs.items():
28 self.attrs[str(k)] = str(v)
29 return self
30
31 def __todom__(self, doc):
32 el = doc.createElementNS(self.ns, self.name)
33 for k, v in self.attrs.items():
34 el.setAttribute(k, v)
35 for child in self.children:
36 el.appendChild(child.__todom__(doc))
37 return el
38
39class context(object):
40 def __init__(self):
41 self.nodeconv = {}
42 self.nodeconv[bytes] = lambda ob: text(ob, "utf-8")
43 self.nodeconv[str] = text
44 self.nodeconv[int] = text
45 self.nodeconv[float] = text
46
47 def nodefrom(self, ob):
48 if isinstance(ob, node):
49 return ob
50 if hasattr(ob, "__tonode__"):
51 return ob.__tonode__()
52 if type(ob) in self.nodeconv:
53 return self.nodeconv[type(ob)](ob)
54 raise Exception("No node conversion known for %s objects" % str(type(ob)))
55
56class constructor(object):
57 def __init__(self, ns, elcls = element, ctx=None):
58 self._ns = ns
59 self._elcls = elcls
60 if ctx is None: ctx = context()
61 self._ctx = ctx
62
63 def __getattr__(self, name):
64 return self._elcls(self._ns, name, self._ctx)