7 if isinstance(el, cons.element):
9 names[el.ns] = u"n" + unicode(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 = (u"'", u"'") if u'"' in buf else (u'"', u""")
71 def shorttag(self, el, **extra):
72 self.write(u'<' + self.elname(el))
73 for k, v in el.attrs.iteritems():
76 for k, v in extra.iteritems():
82 ns = self.nsnames[el.ns]
86 return ns + u':' + el.name
88 def starttag(self, el, **extra):
89 self.write(u'<' + self.elname(el))
90 for k, v in el.attrs.iteritems():
93 for k, v in extra.iteritems():
99 self.write(u'</' + self.elname(el) + u'>')
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(u'<?xml version="1.0" encoding="' + self.charset + u'" ?>\n')
126 self.write(u'<!DOCTYPE %s PUBLIC "%s" "%s">\n' % (self.root.name,
130 for uri, nm in self.nsnames.iteritems():
134 extra[u"xmlns"] = uri
136 extra[u"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()
144 def fragment(cls, out, el, *args, **kw):
145 cls(out=out, root=el, *args, **kw).node(el)
147 def update(self, **ch):
148 ret = type(self).__new__(type(self))
149 ret.__dict__.update(self.__dict__)
150 ret.__dict__.update(ch)
153 class iwriter(object):
154 def __init__(self, out):
159 def write(self, buf):
168 def indent(self, indent):
176 class indenter(formatter):
177 def __init__(self, indent=u" ", *args, **kw):
178 super(indenter, self).__init__(*args, **kw)
179 self.out = iwriter(self.out)
183 def simple(self, el):
184 for ch in el.children:
185 if not isinstance(ch, cons.text):
189 def longtag(self, el, **extra):
190 self.starttag(el, **extra)
193 if not self.simple(el):
194 sub = self.update(curind=self.curind + self.indent)
197 for ch in el.children:
203 def element(self, el, **extra):
204 super(indenter, self).element(el, **extra)
205 if self.out.col > 80 and self.simple(el):
209 self.out.indent(self.curind.encode(self.charset))
212 super(indenter, self).start()