1 import sys, collections
8 def __todom__(self, doc):
9 return doc.createTextNode(self)
12 def __todom__(self, doc):
13 raise Exception("Cannot convert raw code to DOM objects")
16 def __init__(self, ns, name, ctx):
23 def __call__(self, *children, **attrs):
24 for child in children:
25 self.ctx.addchild(self, child)
26 for k, v in attrs.items():
27 self.ctx.addattr(self, k, v)
30 def __todom__(self, doc):
31 el = doc.createElementNS(self.ns, self.name)
32 for k, v in self.attrs.items():
34 for child in self.children:
35 el.appendChild(child.__todom__(doc))
39 doc = xml.dom.minidom.Document()
40 return self.__todom__(doc).toxml()
42 class context(object):
43 charset = (sys.getfilesystemencoding() or "ascii")
47 self.nodeconv[bytes] = lambda ob: text(ob, self.charset)
48 self.nodeconv[str] = text
49 self.nodeconv[int] = text
50 self.nodeconv[float] = text
52 def nodefrom(self, ob):
53 if isinstance(ob, node):
55 if hasattr(ob, "__tonode__"):
56 return ob.__tonode__()
57 if type(ob) in self.nodeconv:
58 return self.nodeconv[type(ob)](ob)
61 def addchild(self, node, child):
64 new = self.nodefrom(child)
66 node.children.append(self.nodefrom(child))
67 elif isinstance(child, collections.Iterable):
69 self.addchild(node, ch)
71 raise Exception("No node conversion known for %s objects" % str(type(ob)))
73 def addattr(self, node, k, v):
75 node.attrs[str(k)] = str(v)
77 class constructor(object):
78 def __init__(self, ns, elcls=element, ctx=None):
81 if ctx is None: ctx = context()
84 def __getattr__(self, name):
85 return self._elcls(self._ns, name, self._ctx)
88 def __init__(self, rootname, pubid, dtdid):
89 self.rootname = rootname