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()
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):
160 for i in range(len(buf)):
169 def indent(self, indent):
177 class indenter(formatter):
178 def __init__(self, indent=" ", *args, **kw):
179 super(indenter, self).__init__(*args, **kw)
180 self.out = iwriter(self.out)
184 def simple(self, el):
185 for ch in el.children:
186 if not isinstance(ch, cons.text):
190 def longtag(self, el, **extra):
191 self.starttag(el, **extra)
194 if not self.simple(el):
195 sub = self.update(curind=self.curind + self.indent)
198 for ch in el.children:
204 def element(self, el, **extra):
205 super(indenter, self).element(el, **extra)
206 if self.out.col > 80 and self.simple(el):
210 self.out.indent(self.curind.encode(self.charset))
213 super(indenter, self).start()