from xml.sax.saxutils import XMLGenerator from xml.sax.xmlreader import AttributesNSImpl def doit(stream): x=XMLGenerator(stream,encoding="utf-8") x.startDocument() x.startPrefixMapping(u"test", u"http://example.org/test") x.startElementNS((u"http://example.org/test",u"tag"),u"tag",AttributesNSImpl({}, {})) x.characters("m\xc3\xb6\xc3\xb6se bite") x.endElementNS((u"http://example.org/test",u"tag"),u"tag") x.endDocument() from StringIO import StringIO from io import BytesIO s=BytesIO() #s=StringIO() doit(s) print s.buflist print s.getvalue()