comparison planemo/lib/python3.7/site-packages/rdflib/plugins/serializers/trix.py @ 1:56ad4e20f292 draft

"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author guerler
date Fri, 31 Jul 2020 00:32:28 -0400
parents
children
comparison
equal deleted inserted replaced
0:d30785e31577 1:56ad4e20f292
1 from rdflib.serializer import Serializer
2 from rdflib.plugins.serializers.xmlwriter import XMLWriter
3
4 from rdflib.term import URIRef, Literal, BNode
5 from rdflib.namespace import Namespace
6
7 from rdflib.graph import Graph, ConjunctiveGraph
8
9 from rdflib.py3compat import b
10
11 __all__ = ['TriXSerializer']
12
13 ## TODO: MOve this somewhere central
14 TRIXNS = Namespace("http://www.w3.org/2004/03/trix/trix-1/")
15 XMLNS = Namespace("http://www.w3.org/XML/1998/namespace")
16
17
18 class TriXSerializer(Serializer):
19 def __init__(self, store):
20 super(TriXSerializer, self).__init__(store)
21 if not store.context_aware:
22 raise Exception(
23 "TriX serialization only makes sense for context-aware stores")
24
25 def serialize(self, stream, base=None, encoding=None, **args):
26
27 nm = self.store.namespace_manager
28
29 self.writer = XMLWriter(stream, nm, encoding, extra_ns={"": TRIXNS})
30
31 self.writer.push(TRIXNS["TriX"])
32 self.writer.namespaces()
33
34 if isinstance(self.store, ConjunctiveGraph):
35 for subgraph in self.store.contexts():
36 self._writeGraph(subgraph)
37 elif isinstance(self.store, Graph):
38 self._writeGraph(self.store)
39 else:
40 raise Exception("Unknown graph type: " + type(self.store))
41
42 self.writer.pop()
43 stream.write(b("\n"))
44
45 def _writeGraph(self, graph):
46 self.writer.push(TRIXNS["graph"])
47 if isinstance(graph.identifier, URIRef):
48 self.writer.element(
49 TRIXNS["uri"], content=str(graph.identifier))
50
51 for triple in graph.triples((None, None, None)):
52 self._writeTriple(triple)
53 self.writer.pop()
54
55 def _writeTriple(self, triple):
56 self.writer.push(TRIXNS["triple"])
57 for component in triple:
58 if isinstance(component, URIRef):
59 self.writer.element(TRIXNS["uri"],
60 content=str(component))
61 elif isinstance(component, BNode):
62 self.writer.element(TRIXNS["id"],
63 content=str(component))
64 elif isinstance(component, Literal):
65 if component.datatype:
66 self.writer.element(TRIXNS["typedLiteral"],
67 content=str(component),
68 attributes={TRIXNS["datatype"]:
69 str(
70 component.datatype)})
71 elif component.language:
72 self.writer.element(TRIXNS["plainLiteral"],
73 content=str(component),
74 attributes={XMLNS["lang"]:
75 str(
76 component.language)})
77 else:
78 self.writer.element(TRIXNS["plainLiteral"],
79 content=str(component))
80 self.writer.pop()