<s> from rdflib . serializer import Serializer <EOL> from rdflib . plugins . serializers . xmlwriter import XMLWriter <EOL> from rdflib . term import URIRef , Literal , BNode <EOL> from rdflib . namespace import Namespace <EOL> from rdflib . graph import Graph , ConjunctiveGraph <EOL> TRIXNS = Namespace ( "<STR_LIT>" ) <EOL> XMLNS = Namespace ( "<STR_LIT>" ) <EOL> class TriXSerializer ( Serializer ) : <EOL> def __init__ ( self , store ) : <EOL> super ( TriXSerializer , self ) . __init__ ( store ) <EOL> def serialize ( self , stream , base = None , encoding = None , ** args ) : <EOL> nm = self . store . namespace_manager <EOL> self . writer = XMLWriter ( stream , nm , encoding , extra_ns = { "<STR_LIT>" : TRIXNS } ) <EOL> self . writer . push ( TRIXNS [ u"<STR_LIT>" ] ) <EOL> self . writer . namespaces ( ) <EOL> if isinstance ( self . store , ConjunctiveGraph ) : <EOL> for subgraph in self . store . contexts ( ) : <EOL> self . _writeGraph ( subgraph ) <EOL> elif isinstance ( self . store , Graph ) : <EOL> self . _writeGraph ( self . store ) <EOL> else : <EOL> raise Exception ( "<STR_LIT>" + type ( self . store ) ) <EOL> self . writer . pop ( ) <EOL> stream . write ( "<STR_LIT:\n>" ) <EOL> def _writeGraph ( self , graph ) : <EOL> self . writer . push ( TRIXNS [ u"<STR_LIT>" ] ) <EOL> if isinstance ( graph . identifier , URIRef ) : <EOL> self . writer . element ( TRIXNS [ u"<STR_LIT>" ] , content = unicode ( graph . identifier ) ) <EOL> for triple in graph . triples ( ( None , None , None ) ) : <EOL> self . _writeTriple ( triple ) <EOL> self . writer . pop ( ) <EOL> def _writeTriple ( self , triple ) : <EOL> self . writer . push ( TRIXNS [ u"<STR_LIT>" ] ) <EOL> for component in triple : <EOL> if isinstance ( component , URIRef ) : <EOL> self . writer . element ( TRIXNS [ u"<STR_LIT>" ] , <EOL> content = unicode ( component ) ) <EOL> elif isinstance ( component , BNode ) : <EOL> self . writer . element ( TRIXNS [ u"<STR_LIT:id>" ] , <EOL> content = unicode ( component ) ) <EOL> elif isinstance ( component , Literal ) : <EOL> if component . datatype : <EOL> self . writer . element ( TRIXNS [ u"<STR_LIT>" ] , <EOL> content = unicode ( component ) , <EOL> attributes = { TRIXNS [ u"<STR_LIT>" ] : unicode ( component . datatype ) } ) <EOL> elif component . language : <EOL> self . writer . element ( TRIXNS [ u"<STR_LIT>" ] , <EOL> content = unicode ( component ) , <EOL> attributes = { XMLNS [ u"<STR_LIT>" ] : unicode ( component . language ) } ) <EOL> else : <EOL> self . writer . element ( TRIXNS [ u"<STR_LIT>" ] , <EOL> content = unicode ( component ) ) <EOL> self . writer . pop ( ) </s>
