Source code

Download source archive ↓

src/rdflib/plugins/serializers/trix.py

1from __future__ import annotations
2
3from typing import IO, Any, Optional
4
5from rdflib.graph import ConjunctiveGraph, Graph
6from rdflib.namespace import Namespace
7from rdflib.plugins.serializers.xmlwriter import XMLWriter
8from rdflib.serializer import Serializer
9from rdflib.term import BNode, Literal, URIRef
10
11__all__ = ["TriXSerializer"]
12
13# TODO: Move this somewhere central
14TRIXNS = Namespace("http://www.w3.org/2004/03/trix/trix-1/")
15XMLNS = Namespace("http://www.w3.org/XML/1998/namespace")
16
17
18class TriXSerializer(Serializer):
19    """TriX RDF graph serializer."""
20
21    def __init__(self, store: Graph):
22        super(TriXSerializer, self).__init__(store)
23        if not store.context_aware:
24            raise Exception(
25                "TriX serialization only makes sense for context-aware stores"
26            )
27
28    def serialize(
29        self,
30        stream: IO[bytes],
31        base: Optional[str] = None,
32        encoding: Optional[str] = None,
33        **kwargs: Any,
34    ) -> None:
35        nm = self.store.namespace_manager
36
37        self.writer = XMLWriter(stream, nm, encoding, extra_ns={"": TRIXNS})
38
39        self.writer.push(TRIXNS["TriX"])
40        # if base is given here, use that, if not and a base is set for the graph use that
41        if base is None and self.store.base is not None:
42            base = self.store.base
43        if base is not None:
44            self.writer.attribute("http://www.w3.org/XML/1998/namespacebase", base)
45        self.writer.namespaces()
46
47        if isinstance(self.store, ConjunctiveGraph):
48            for subgraph in self.store.contexts():
49                self._writeGraph(subgraph)
50        elif isinstance(self.store, Graph):
51            self._writeGraph(self.store)
52        else:
53            raise Exception(f"Unknown graph type: {type(self.store)}")
54
55        self.writer.pop()
56        stream.write("\n".encode("latin-1"))
57
58    def _writeGraph(self, graph):  # noqa: N802
59        self.writer.push(TRIXNS["graph"])
60        if graph.base:
61            self.writer.attribute(
62                "http://www.w3.org/XML/1998/namespacebase", graph.base
63            )
64        if isinstance(graph.identifier, URIRef):
65            self.writer.element(TRIXNS["uri"], content=str(graph.identifier))
66
67        for triple in graph.triples((None, None, None)):
68            self._writeTriple(triple)
69        self.writer.pop()
70
71    def _writeTriple(self, triple):  # noqa: N802
72        self.writer.push(TRIXNS["triple"])
73        for component in triple:
74            if isinstance(component, URIRef):
75                self.writer.element(TRIXNS["uri"], content=str(component))
76            elif isinstance(component, BNode):
77                self.writer.element(TRIXNS["id"], content=str(component))
78            elif isinstance(component, Literal):
79                if component.datatype:
80                    self.writer.element(
81                        TRIXNS["typedLiteral"],
82                        content=str(component),
83                        attributes={TRIXNS["datatype"]: str(component.datatype)},
84                    )
85                elif component.language:
86                    self.writer.element(
87                        TRIXNS["plainLiteral"],
88                        content=str(component),
89                        attributes={XMLNS["lang"]: str(component.language)},
90                    )
91                else:
92                    self.writer.element(TRIXNS["plainLiteral"], content=str(component))
93        self.writer.pop()