Skip to content

# `` trix

A TriX parser for RDFLib

Classes:

- `TriXHandler` –

  An Sax Handler for TriX. See http://sw.nokia.com/trix/

- `TriXParser` –

  A parser for TriX. See http://sw.nokia.com/trix/

Functions:

- `create_parser` –

## `` TRIXNS `module-attribute`

    TRIXNS = Namespace('http://www.w3.org/2004/03/trix/trix-1/')

## `` XMLNS `module-attribute`

    XMLNS = Namespace('http://www.w3.org/XML/1998/namespace')

## `` __all__ `module-attribute`

    __all__ = ['create_parser', 'TriXHandler', 'TriXParser']

## `` TriXHandler

    TriXHandler(store: Store)

Bases: `ContentHandler`

An Sax Handler for TriX. See http://sw.nokia.com/trix/

Methods:

- `characters` –
- `endElementNS` –
- `endPrefixMapping` –
- `error` –
- `get_bnode` –
- `ignorableWhitespace` –
- `processingInstruction` –
- `reset` –
- `setDocumentLocator` –
- `startDocument` –
- `startElementNS` –
- `startPrefixMapping` –

Attributes:

- `datatype` (`Optional[str]`) –
- `lang` (`Optional[str]`) –
- `preserve_bnode_ids` –
- `store` –

Source code in `rdflib/plugins/parsers/trix.py`

    35
    36
    37
    38

    def __init__(self, store: Store):
        self.store = store
        self.preserve_bnode_ids = False
        self.reset()

### `` datatype `instance-attribute`

    datatype: Optional[str]

### `` lang `instance-attribute`

    lang: Optional[str]

### `` preserve_bnode_ids `instance-attribute`

    preserve_bnode_ids = False

### `` store `instance-attribute`

    store = store

### `` characters

    characters(content: str) -> None

Source code in `rdflib/plugins/parsers/trix.py`

    241
    242

    def characters(self, content: str) -> None:
        self.chars += content

### `` endElementNS

    endElementNS(name: Tuple[Optional[str], str], qname) -> None

Source code in `rdflib/plugins/parsers/trix.py`

    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228

    def endElementNS(self, name: Tuple[Optional[str], str], qname) -> None:
        if TYPE_CHECKING:
            assert self.triple is not None
        if name[0] != str(TRIXNS):
            self.error(
                "Only elements in the TriX namespace are allowed. %s!=%s"
                % (name[0], TRIXNS)
            )

        if name[1] == "uri":
            if self.state == 3:
                self.graph = Graph(
                    store=self.store, identifier=URIRef(self.chars.strip())
                )
                self.state = 2
            elif self.state == 4:
                self.triple += [URIRef(self.chars.strip())]
            else:
                self.error(
                    "Illegal internal self.state - This should never "
                    + "happen if the SAX parser ensures XML syntax correctness"
                )

        elif name[1] == "id":
            if self.state == 3:
                self.graph = Graph(
                    self.store, identifier=self.get_bnode(self.chars.strip())
                )
                self.state = 2
            elif self.state == 4:
                self.triple += [self.get_bnode(self.chars.strip())]
            else:
                self.error(
                    "Illegal internal self.state - This should never "
                    + "happen if the SAX parser ensures XML syntax correctness"
                )

        elif name[1] == "plainLiteral" or name[1] == "typedLiteral":
            if self.state == 4:
                self.triple += [
                    Literal(self.chars, lang=self.lang, datatype=self.datatype)
                ]
            else:
                self.error(
                    "This should never happen if the SAX parser "
                    + "ensures XML syntax correctness"
                )

        elif name[1] == "triple":
            if self.state == 4:
                if len(self.triple) != 3:
                    self.error(
                        "Triple has wrong length, got %d elements: %s"
                        % (len(self.triple), self.triple)
                    )
                # type error: Item "None" of "Optional[Graph]" has no attribute "add"
                # type error: Argument 1 to "add" of "Graph" has incompatible type "List[Identifier]"; expected "Tuple[Node, Node, Node]"
                self.graph.add(self.triple)  # type: ignore[union-attr, arg-type]
                # self.store.store.add(self.triple,context=self.graph)
                # self.store.addN([self.triple+[self.graph]])
                self.state = 2
            else:
                self.error(
                    "This should never happen if the SAX parser "
                    + "ensures XML syntax correctness"
                )

        elif name[1] == "graph":
            self.graph = None
            self.state = 1

        elif name[1].lower() == "trix":
            self.state = 0

        else:
            self.error("Unexpected close element")

### `` endPrefixMapping

    endPrefixMapping(prefix: Optional[str]) -> None

Source code in `rdflib/plugins/parsers/trix.py`

    59
    60

    def endPrefixMapping(self, prefix: Optional[str]) -> None:
        pass

### `` error

    error(message: str) -> NoReturn

Source code in `rdflib/plugins/parsers/trix.py`

    250
    251
    252
    253
    254
    255
    256
    257

    def error(self, message: str) -> NoReturn:
        locator = self.locator
        info = "%s:%s:%s: " % (
            locator.getSystemId(),
            locator.getLineNumber(),
            locator.getColumnNumber(),
        )
        raise ParserError(info + message)

### `` get_bnode

    get_bnode(label: str) -> BNode

Source code in `rdflib/plugins/parsers/trix.py`

    230
    231
    232
    233
    234
    235
    236
    237
    238
    239

    def get_bnode(self, label: str) -> BNode:
        if self.preserve_bnode_ids:
            bn = BNode(label)
        else:
            if label in self.bnode:
                bn = self.bnode[label]
            else:
                bn = BNode(label)
                self.bnode[label] = bn
        return bn

### `` ignorableWhitespace

    ignorableWhitespace(content) -> None

Source code in `rdflib/plugins/parsers/trix.py`

    244
    245

    def ignorableWhitespace(self, content) -> None:
        pass

### `` processingInstruction

    processingInstruction(target, data) -> None

Source code in `rdflib/plugins/parsers/trix.py`

    247
    248

    def processingInstruction(self, target, data) -> None:
        pass

### `` reset

    reset() -> None

Source code in `rdflib/plugins/parsers/trix.py`

    40
    41
    42
    43
    44
    45
    46

    def reset(self) -> None:
        self.bnode: Dict[str, BNode] = {}
        self.graph: Optional[Graph] = None
        self.triple: Optional[List[Identifier]] = None
        self.state = 0
        self.lang = None
        self.datatype = None

### `` setDocumentLocator

    setDocumentLocator(locator: Locator)

Source code in `rdflib/plugins/parsers/trix.py`

    50
    51

    def setDocumentLocator(self, locator: Locator):
        self.locator = locator

### `` startDocument

    startDocument() -> None

Source code in `rdflib/plugins/parsers/trix.py`

    53
    54

    def startDocument(self) -> None:
        pass

### `` startElementNS

    startElementNS(name: Tuple[Optional[str], str], qname, attrs: AttributesImpl) -> None

Source code in `rdflib/plugins/parsers/trix.py`

     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151

    def startElementNS(
        self, name: Tuple[Optional[str], str], qname, attrs: AttributesImpl
    ) -> None:
        if name[0] != str(TRIXNS):
            self.error(
                "Only elements in the TriX namespace are allowed. %s!=%s"
                % (name[0], TRIXNS)
            )

        if name[1].lower() == "trix":
            if self.state == 0:
                self.state = 1
            else:
                self.error("Unexpected TriX element")

        elif name[1] == "graph":
            if self.state == 1:
                self.state = 2
            else:
                self.error("Unexpected graph element")

        elif name[1] == "uri":
            if self.state == 2:
                # the context uri
                self.state = 3
            elif self.state == 4:
                # part of a triple
                pass
            else:
                self.error("Unexpected uri element")

        elif name[1] == "triple":
            if self.state == 2:
                if self.graph is None:
                    # anonymous graph, create one with random bnode id
                    self.graph = Graph(store=self.store)
                # start of a triple
                self.triple = []
                self.state = 4
            else:
                self.error("Unexpected triple element")

        elif name[1] == "typedLiteral":
            if self.state == 4:
                # part of triple
                self.lang = None
                self.datatype = None

                try:
                    self.lang = attrs.getValue((str(XMLNS), "lang"))  # type: ignore[arg-type, unused-ignore]
                except Exception:
                    # language not required - ignore
                    pass
                try:
                    self.datatype = attrs.getValueByQName("datatype")  # type: ignore[arg-type, unused-ignore]
                except KeyError:
                    self.error("No required attribute 'datatype'")
            else:
                self.error("Unexpected typedLiteral element")

        elif name[1] == "plainLiteral":
            if self.state == 4:
                # part of triple
                self.lang = None
                self.datatype = None
                try:
                    # type error: Argument 1 to "getValue" of "AttributesImpl" has incompatible type "Tuple[str, str]"; expected "str"
                    self.lang = attrs.getValue((str(XMLNS), "lang"))  # type: ignore[arg-type, unused-ignore]
                except Exception:
                    # language not required - ignore
                    pass

            else:
                self.error("Unexpected plainLiteral element")

        elif name[1] == "id":
            if self.state == 2:
                # the context uri
                self.state = 3

            elif self.state == 4:
                # part of triple
                pass
            else:
                self.error("Unexpected id element")

        else:
            self.error("Unknown element %s in TriX namespace" % name[1])

        self.chars = ""

### `` startPrefixMapping

    startPrefixMapping(prefix: Optional[str], namespace: str) -> None

Source code in `rdflib/plugins/parsers/trix.py`

    56
    57

    def startPrefixMapping(self, prefix: Optional[str], namespace: str) -> None:
        pass

## `` TriXParser

    TriXParser()

Bases: `Parser`

A parser for TriX. See http://sw.nokia.com/trix/

Methods:

- `parse` –

Source code in `rdflib/plugins/parsers/trix.py`

    279
    280

    def __init__(self):
        pass

### `` parse

    parse(source: InputSource, sink: Graph, **args: Any) -> None

Source code in `rdflib/plugins/parsers/trix.py`

    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296

    def parse(self, source: InputSource, sink: Graph, **args: Any) -> None:
        assert (
            sink.store.context_aware
        ), "TriXParser must be given a context aware store."

        self._parser = create_parser(sink.store)
        content_handler = self._parser.getContentHandler()
        preserve_bnode_ids = args.get("preserve_bnode_ids", None)
        if preserve_bnode_ids is not None:
            # type error: ContentHandler has no attribute "preserve_bnode_ids"
            content_handler.preserve_bnode_ids = preserve_bnode_ids  # type: ignore[attr-defined, unused-ignore]
        # We're only using it once now
        # content_handler.reset()
        # self._parser.reset()
        self._parser.parse(source)

## `` create_parser

    create_parser(store: Store) -> XMLReader

Source code in `rdflib/plugins/parsers/trix.py`

    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273

    def create_parser(store: Store) -> XMLReader:
        parser = make_parser()
        try:
            # Workaround for bug in expatreader.py. Needed when
            # expatreader is trying to guess a prefix.
            # type error: "XMLReader" has no attribute "start_namespace_decl"
            parser.start_namespace_decl("xml", "http://www.w3.org/XML/1998/namespace")  # type: ignore[attr-defined]
        except AttributeError:
            pass  # Not present in Jython (at least)
        parser.setFeature(handler.feature_namespaces, 1)
        trix = TriXHandler(store)
        parser.setContentHandler(trix)
        parser.setErrorHandler(ErrorHandler())
        return parser