Get or construct RDF Statements (Triples)

An raptor_statement containing the triple terms and optional graph term can be made either by receiving them from a raptor_parser via parsing or can be constructed by hand.

When constructing by hand, the raptor_statement structure should be allocated by the application and the fields filled in. Each statement has three triple terms (subject, predicate, object) and an optional graph term. The subject can be a URI or blank node, the predicate can only be a URI and the object can be a URI, blank node or RDF literal. RDF literals can have either just a Unicode string, a Unicode string and a language or a Unicode string and a datatype URI.

The statement terms are all instances of raptor_term objects constructed with the appropriate constructor for the URI, blank node or rdf literal types. The graph term of the statement is typically a URI or blank node.

Example 3. rdfserialize.c: Serialize 1 triple to RDF/XML (Abbreviated)

#include <stdio.h>
#include <raptor2.h>
#include <stdlib.h>

/* rdfserialize.c: serialize 1 triple to RDF/XML-Abbrev */

int
main(int argc, char *argv[])
{
  raptor_world *world = NULL;
  raptor_serializer* rdf_serializer = NULL;
  unsigned char *uri_string;
  raptor_uri *base_uri;
  raptor_statement* triple;

  world = raptor_new_world();
  
  uri_string = raptor_uri_filename_to_uri_string(argv[1]);
  base_uri = raptor_new_uri(world, uri_string);

  rdf_serializer = raptor_new_serializer(world, "rdfxml-abbrev");
  raptor_serializer_start_to_file_handle(rdf_serializer, base_uri, stdout);
  
  /* Make a triple with URI subject, URI predicate, literal object */
  triple = raptor_new_statement(world);
  triple->subject = raptor_new_term_from_uri_string(world, (const unsigned char*)"http://example.org/subject");
  triple->predicate = raptor_new_term_from_uri_string(world, (const unsigned char*)"http://example.org/predicate");
  triple->object = raptor_new_term_from_literal(world,
                                                (const unsigned char*)"An example literal",
                                                NULL,
                                                (const unsigned char*)"en");

  /* Write the triple */
  raptor_serializer_serialize_statement(rdf_serializer, triple);

  /* Delete the triple */
  raptor_free_statement(triple);

  raptor_serializer_serialize_end(rdf_serializer);
  raptor_free_serializer(rdf_serializer);
  
  raptor_free_uri(base_uri);
  raptor_free_memory(uri_string);

  raptor_free_world(world);
  return 0;
}

Compile it like this:

$ gcc -o rdfserialize rdfserialize.c `pkg-config raptor2 --cflags --libs`

and run it with an optional base URI argument

$ ./rdfserialize
<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
  <rdf:Description rdf:about="http://example.org/subject">
    <ns0:predicate xmlns:ns0="http://example.org/" xml:lang="en">An example</ns0:predicate>
  </rdf:Description>
</rdf:RDF>