Package RDFClosure :: Package serializers :: Module XMLWriter
[hide private]
[frames] | no frames]

Source Code for Module RDFClosure.serializers.XMLWriter

 1  """ 
 2   
 3  XML Writer to be used by the L{PrettyXMLSerializer} module. This is a slightly modified version of RDFLib's  
 4  original XML Writer module, the changes are essentially aesthetic in nature (removing the unnecessary CDATA sections,  
 5  using double quotes everywhere for attributes (both for namespaces and attributes in general). 
 6   
 7  """ 
 8   
 9  import codecs 
10  from xml.sax.saxutils import quoteattr, escape 
11   
12 -class XMLWriter(object):
13 - def __init__(self, stream, namespace_manager, encoding=None, decl=1):
14 encoding = encoding or 'utf-8' 15 encoder, decoder, stream_reader, stream_writer = codecs.lookup(encoding) 16 self.stream = stream = stream_writer(stream) 17 if decl: 18 stream.write('<?xml version="1.0" encoding="%s"?>' % encoding) 19 self.element_stack = [] 20 self.nm = namespace_manager 21 self.closed = True
22
23 - def __get_indent(self):
24 return " " * len(self.element_stack)
25 indent = property(__get_indent) 26
27 - def __close_start_tag(self):
28 if not self.closed: # TODO: 29 self.closed = True 30 self.stream.write(">")
31
32 - def push(self, uri):
33 nm = self.nm 34 self.__close_start_tag() 35 write = self.stream.write 36 write("\n") 37 write(self.indent) 38 write("<%s" % nm.qname(uri)) 39 self.element_stack.append(uri) 40 self.closed = False 41 self.parent = False
42
43 - def pop(self, uri=None):
44 top = self.element_stack.pop() 45 if uri: 46 assert uri==top 47 write = self.stream.write 48 if not self.closed: 49 self.closed = True 50 write("/>") 51 else: 52 if self.parent: 53 write("\n") 54 write(self.indent) 55 write("</%s>" % self.nm.qname(uri)) 56 self.parent = True
57
58 - def namespaces(self, namespaces):
59 write = self.stream.write 60 write("\n") 61 for prefix, namespace in namespaces: 62 if prefix: 63 write(' xmlns:%s="%s"\n' % (prefix, namespace)) 64 else: 65 write(' xmlns="%s"\n' % namespace)
66
67 - def attribute(self, uri, value):
68 write = self.stream.write 69 write(" %s=%s" % (self.nm.qname(uri), quoteattr(value)))
70
71 - def text(self, text, to_escape):
72 self.__close_start_tag() 73 if to_escape : 74 self.stream.write(escape(text)) 75 else : 76 self.stream.write(text)
77 # if "<" in text and ">" in text and not "]]>" in text: 78 # #self.stream.write("<![CDATA[") 79 # self.stream.write(text) 80 # #self.stream.write("]]>") 81 # else: 82 # self.stream.write(escape(text)) 83