rdf_core 0.9.0
rdf_core: ^0.9.0 copied to clipboard
A type-safe, modular Dart library for modeling, encoding, and decoding RDF data.
example/main.dart
// Example usage of the rdf_core package
// Demonstrates manual graph handling, Turtle, and JSON-LD parsing/serialization
//
import 'package:rdf_core/rdf_core.dart';
void main() {
// --- Manual Graph Construction ---
// NOTE: Always use canonical RDF vocabularies (e.g., http://xmlns.com/foaf/0.1/) with http://, not https://
final alice = IriTerm('http://example.org/alice');
final bob = IriTerm('http://example.org/bob');
final knows = IriTerm('http://xmlns.com/foaf/0.1/knows');
final name = IriTerm('http://xmlns.com/foaf/0.1/name');
final graph = RdfGraph(
triples: [
Triple(alice, knows, bob),
// Note the LiteralTerm.string convenience constructor which is the same as LiteralTerm('Alice', datatype: Xsd.string)
Triple(alice, name, LiteralTerm.string('Alice')),
Triple(bob, name, LiteralTerm.string('Bob')),
],
);
print('Manual RDF Graph:');
for (final triple in graph.triples) {
print(' ${triple.subject} ${triple.predicate} ${triple.object}');
}
// --- Serialize to Turtle ---
final turtleStr = turtle.encode(graph);
// Note that prefixes for well-known IRIs like https://xmlns.com/foaf/0.1/ will automatically
// be introduced (if needed). Other prefixes for the IRI terms in the graph will be generated automatically.
print('\nTurtle encoding:\n$turtleStr');
// --- Parse from Turtle ---
final parsedGraph = turtle.decode(turtleStr);
print('\nDecoded from Turtle:');
for (final triple in parsedGraph.triples) {
print(' ${triple.subject} ${triple.predicate} ${triple.object}');
}
// --- Or: Make use of Codec Registration ---
// We can use the codecs for turtle, ntriples, jsonld etc. directly like above,
// or we can get them from the RDF Core instance to use them based on the content type.
//
// Note that this way, also a contentType of null is allowed, which will
// automatically detect the decoder format based on the input string and use
// the first registered codec as encoder (typically turtle).
final contentType =
'application/ld+json'; // or 'text/turtle', 'application/n-triples', etc.
final codec = rdf.codec(contentType: contentType);
// --- Serialize to JSON-LD ---
final encoded = codec.encode(graph);
print('\nJSON-LD serialization:\n$encoded');
// --- Parse from JSON-LD ---
final decoded = codec.decode(encoded);
print('\nParsed from JSON-LD:');
for (final triple in decoded.triples) {
print(' ${triple.subject} ${triple.predicate} ${triple.object}');
}
// -- Serialize to Turtle with custom codec that has specific prefixes --
final customCodec = turtle.withOptions(
encoder: RdfGraphEncoderOptions(
customPrefixes: {
'exam': 'http://example.org/',
'foaf': 'http://xmlns.com/foaf/0.1/',
},
),
);
final decoded2 = customCodec.encode(graph);
print('\nCustom Turtle serialization:\n$decoded2');
}