7 if isinstance(el, cons.element):
9 names[el.ns] = "n" + str(nid[0])
11 for ch in el.children:
20 class formatter(object):
21 def __init__(self, out, root, nsnames=None, charset="utf-8", doctype=None):
24 nsnames = findnsnames(root)
25 self.nsnames = nsnames
27 self.charset = charset
28 self.doctype = doctype
30 def write(self, text):
31 self.out.write(text.encode(self.charset))
33 def quotewrite(self, buf):
47 def rawcode(self, el):
50 def attrval(self, buf):
51 qc, qt = ("'", "'") if '"' in buf else ('"', """)
71 def shorttag(self, el, **extra):
72 self.write('<' + self.elname(el))
73 for k, v in el.attrs.items():
76 for k, v in extra.items():
82 ns = self.nsnames[el.ns]
86 return ns + ':' + el.name
88 def starttag(self, el, **extra):
89 self.write('<' + self.elname(el))
90 for k, v in el.attrs.items():
93 for k, v in extra.items():
99 self.write('</' + self.elname(el) + '>')
101 def longtag(self, el):
102 self.starttag(el, **extra)
103 for ch in el.children:
107 def element(self, el, **extra):
108 if len(el.children) == 0:
109 self.shorttag(el, **extra)
111 self.longtag(el, **extra)
114 if isinstance(el, cons.element):
116 elif isinstance(el, cons.text):
118 elif isinstance(el, cons.raw):
121 raise Exception("Unknown object in element tree: " + el)
124 self.write('<?xml version="1.0" encoding="' + self.charset + '" ?>\n')
126 self.write('<!DOCTYPE %s PUBLIC "%s" "%s">\n' % (self.root.name,
130 for uri, nm in self.nsnames.items():
136 extra["xmlns:" + nm] = uri
137 self.element(self.root, **extra)
140 def output(cls, out, el, *args, **kw):
141 cls(out=out, root=el, *args, **kw).start()
143 def update(self, **ch):
144 ret = type(self).__new__(type(self))
145 ret.__dict__.update(self.__dict__)
146 ret.__dict__.update(ch)
149 class iwriter(object):
150 def __init__(self, out):
155 def write(self, buf):
156 for i in range(len(buf)):
165 def indent(self, indent):
173 class indenter(formatter):
174 def __init__(self, indent=" ", *args, **kw):
175 super(indenter, self).__init__(*args, **kw)
176 self.out = iwriter(self.out)
180 def simple(self, el):
181 for ch in el.children:
182 if not isinstance(ch, cons.text):
186 def longtag(self, el, **extra):
187 self.starttag(el, **extra)
190 if not self.simple(el):
191 sub = self.update(curind=self.curind + self.indent)
194 for ch in el.children:
200 def element(self, el, **extra):
201 super(indenter, self).element(el, **extra)
202 if self.out.col > 80 and self.simple(el):
206 self.out.indent(self.curind.encode(self.charset))
209 super(indenter, self).start()